Raw Write() Returned Invalid Length 110 (Should Have Been Between 0 and 55)
Release Notes¶
Version History¶
This table tracks the meta-package versions and the version of each Qiskit element installed:
Qiskit Metapackage Version | qiskit-terra | qiskit-aer | qiskit-ignis | qiskit-ibmq-provider | qiskit-aqua | Release Date |
---|---|---|---|---|---|---|
0.33.1 | 0.19.1 | 0.9.1 | 0.7.0 | 0.18.2 | 2021-12-10 | |
0.33.0 | 0.19.0 | 0.9.1 | 0.7.0 | 0.18.1 | 2021-12-06 | |
0.32.1 | 0.18.3 | 0.9.1 | 0.6.0 | 0.18.1 | 0.9.5 | 2021-11-22 |
0.32.0 | 0.18.3 | 0.9.1 | 0.6.0 | 0.18.0 | 0.9.5 | 2021-11-10 |
0.31.0 | 0.18.3 | 0.9.1 | 0.6.0 | 0.17.0 | 0.9.5 | 2021-10-12 |
0.30.1 | 0.18.3 | 0.9.0 | 0.6.0 | 0.16.0 | 0.9.5 | 2021-09-29 |
0.30.0 | 0.18.2 | 0.9.0 | 0.6.0 | 0.16.0 | 0.9.5 | 2021-09-16 |
0.29.1 | 0.18.2 | 0.8.2 | 0.6.0 | 0.16.0 | 0.9.5 | 2021-09-10 |
0.29.0 | 0.18.1 | 0.8.2 | 0.6.0 | 0.16.0 | 0.9.4 | 2021-08-02 |
0.28.0 | 0.18.0 | 0.8.2 | 0.6.0 | 0.15.0 | 0.9.4 | 2021-07-13 |
0.27.0 | 0.17.4 | 0.8.2 | 0.6.0 | 0.14.0 | 0.9.2 | 2021-06-15 |
0.26.2 | 0.17.4 | 0.8.2 | 0.6.0 | 0.13.1 | 0.9.1 | 2021-05-19 |
0.26.1 | 0.17.4 | 0.8.2 | 0.6.0 | 0.13.1 | 0.9.1 | 2021-05-18 |
0.26.0 | 0.17.3 | 0.8.2 | 0.6.0 | 0.13.1 | 0.9.1 | 2021-05-11 |
0.25.4 | 0.17.2 | 0.8.2 | 0.6.0 | 0.12.3 | 0.9.1 | 2021-05-05 |
0.25.3 | 0.17.1 | 0.8.2 | 0.6.0 | 0.12.3 | 0.9.1 | 2021-04-29 |
0.25.2 | 0.17.1 | 0.8.1 | 0.6.0 | 0.12.3 | 0.9.1 | 2021-04-21 |
0.25.1 | 0.17.1 | 0.8.1 | 0.6.0 | 0.12.2 | 0.9.1 | 2021-04-15 |
0.25.0 | 0.17.0 | 0.8.0 | 0.6.0 | 0.12.2 | 0.9.0 | 2021-04-02 |
0.24.1 | 0.16.4 | 0.7.6 | 0.5.2 | 0.12.2 | 0.8.2 | 2021-03-24 |
0.24.0 | 0.16.4 | 0.7.6 | 0.5.2 | 0.12.1 | 0.8.2 | 2021-03-04 |
0.23.6 | 0.16.4 | 0.7.5 | 0.5.2 | 0.11.1 | 0.8.2 | 2021-02-18 |
0.23.5 | 0.16.4 | 0.7.4 | 0.5.2 | 0.11.1 | 0.8.2 | 2021-02-08 |
0.23.4 | 0.16.3 | 0.7.3 | 0.5.1 | 0.11.1 | 0.8.1 | 2021-01-28 |
0.23.3 | 0.16.2 | 0.7.3 | 0.5.1 | 0.11.1 | 0.8.1 | 2021-01-26 |
0.23.2 | 0.16.1 | 0.7.2 | 0.5.1 | 0.11.1 | 0.8.1 | 2020-12-15 |
0.23.1 | 0.16.1 | 0.7.1 | 0.5.1 | 0.11.1 | 0.8.1 | 2020-11-12 |
0.23.0 | 0.16.0 | 0.7.0 | 0.5.0 | 0.11.0 | 0.8.0 | 2020-10-16 |
0.22.0 | 0.15.2 | 0.6.1 | 0.4.0 | 0.10.0 | 0.7.5 | 2020-10-05 |
0.21.0 | 0.15.2 | 0.6.1 | 0.4.0 | 0.9.0 | 0.7.5 | 2020-09-16 |
0.20.1 | 0.15.2 | 0.6.1 | 0.4.0 | 0.8.0 | 0.7.5 | 2020-09-08 |
0.20.0 | 0.15.1 | 0.6.1 | 0.4.0 | 0.8.0 | 0.7.5 | 2020-08-10 |
0.19.6 | 0.14.2 | 0.5.2 | 0.3.3 | 0.7.2 | 0.7.3 | 2020-06-25 |
0.19.5 | 0.14.2 | 0.5.2 | 0.3.2 | 0.7.2 | 0.7.3 | 2020-06-19 |
0.19.4 | 0.14.2 | 0.5.2 | 0.3.0 | 0.7.2 | 0.7.2 | 2020-06-16 |
0.19.3 | 0.14.1 | 0.5.2 | 0.3.0 | 0.7.2 | 0.7.1 | 2020-06-02 |
0.19.2 | 0.14.1 | 0.5.1 | 0.3.0 | 0.7.1 | 0.7.1 | 2020-05-14 |
0.19.1 | 0.14.1 | 0.5.1 | 0.3.0 | 0.7.0 | 0.7.0 | 2020-05-01 |
0.19.0 | 0.14.0 | 0.5.1 | 0.3.0 | 0.7.0 | 0.7.0 | 2020-04-30 |
0.18.3 | 0.13.0 | 0.5.1 | 0.3.0 | 0.6.1 | 0.6.6 | 2020-04-24 |
0.18.2 | 0.13.0 | 0.5.0 | 0.3.0 | 0.6.1 | 0.6.6 | 2020-04-23 |
0.18.1 | 0.13.0 | 0.5.0 | 0.3.0 | 0.6.0 | 0.6.6 | 2020-04-20 |
0.18.0 | 0.13.0 | 0.5.0 | 0.3.0 | 0.6.0 | 0.6.5 | 2020-04-09 |
0.17.0 | 0.12.0 | 0.4.1 | 0.2.0 | 0.6.0 | 0.6.5 | 2020-04-01 |
0.16.2 | 0.12.0 | 0.4.1 | 0.2.0 | 0.5.0 | 0.6.5 | 2020-03-20 |
0.16.1 | 0.12.0 | 0.4.1 | 0.2.0 | 0.5.0 | 0.6.4 | 2020-03-05 |
0.16.0 | 0.12.0 | 0.4.0 | 0.2.0 | 0.5.0 | 0.6.4 | 2020-02-27 |
0.15.0 | 0.12.0 | 0.4.0 | 0.2.0 | 0.4.6 | 0.6.4 | 2020-02-06 |
0.14.1 | 0.11.1 | 0.3.4 | 0.2.0 | 0.4.5 | 0.6.2 | 2020-01-07 |
0.14.0 | 0.11.0 | 0.3.4 | 0.2.0 | 0.4.4 | 0.6.1 | 2019-12-10 |
0.13.0 | 0.10.0 | 0.3.2 | 0.2.0 | 0.3.3 | 0.6.1 | 2019-10-17 |
0.12.2 | 0.9.1 | 0.3.0 | 0.2.0 | 0.3.3 | 0.6.0 | 2019-10-11 |
0.12.1 | 0.9.0 | 0.3.0 | 0.2.0 | 0.3.3 | 0.6.0 | 2019-09-30 |
0.12.0 | 0.9.0 | 0.3.0 | 0.2.0 | 0.3.2 | 0.6.0 | 2019-08-22 |
0.11.2 | 0.8.2 | 0.2.3 | 0.1.1 | 0.3.2 | 0.5.5 | 2019-08-20 |
0.11.1 | 0.8.2 | 0.2.3 | 0.1.1 | 0.3.1 | 0.5.3 | 2019-07-24 |
0.11.0 | 0.8.2 | 0.2.3 | 0.1.1 | 0.3.0 | 0.5.2 | 2019-07-15 |
0.10.5 | 0.8.2 | 0.2.1 | 0.1.1 | 0.2.2 | 0.5.2 | 2019-06-27 |
0.10.4 | 0.8.2 | 0.2.1 | 0.1.1 | 0.2.2 | 0.5.1 | 2019-06-17 |
0.10.3 | 0.8.1 | 0.2.1 | 0.1.1 | 0.2.2 | 0.5.1 | 2019-05-29 |
0.10.2 | 0.8.0 | 0.2.1 | 0.1.1 | 0.2.2 | 0.5.1 | 2019-05-24 |
0.10.1 | 0.8.0 | 0.2.0 | 0.1.1 | 0.2.2 | 0.5.0 | 2019-05-07 |
0.10.0 | 0.8.0 | 0.2.0 | 0.1.1 | 0.2.1 | 0.5.0 | 2019-05-06 |
0.9.0 | 0.8.0 | 0.2.0 | 0.1.1 | 0.1.1 | 0.5.0 | 2019-05-02 |
0.8.1 | 0.7.2 | 0.1.1 | 0.1.0 | 2019-05-01 | ||
0.8.0 | 0.7.1 | 0.1.1 | 0.1.0 | 2019-03-05 | ||
0.7.3 | >=0.7,<0.8 | >=0.1,<0.2 | 2019-02-19 | |||
0.7.2 | >=0.7,<0.8 | >=0.1,<0.2 | 2019-01-22 | |||
0.7.1 | >=0.7,<0.8 | >=0.1,<0.2 | 2019-01-17 | |||
0.7.0 | >=0.7,<0.8 | >=0.1,<0.2 | 2018-12-14 |
Note
For the 0.7.0
, 0.7.1
, and 0.7.2
meta-package releases the Qiskit Versioning policy was not formalized yet.
Notable Changes¶
Qiskit 0.33.1¶
Terra 0.19.1¶
Prelude¶
Qiskit Terra 0.19.1 is a bugfix release, solving some issues in 0.19.0 concerning circuits constructed by the control-flow builder interface, conditional gates and QPY serialisation of newer Terra objects.
Deprecation Notes¶
-
The loose functions
qiskit.circuit.measure.measure()
andqiskit.circuit.reset.reset()
are deprecated, and will be removed in a future release. Instead, you should access these as methods onQuantumCircuit
:from qiskit import QuantumCircuit circuit = QuantumCircuit ( 1 , 1 ) # Replace this deprecated form ... from qiskit.circuit.measure import measure measure ( circuit , 0 , 0 ) # ... with either of the next two lines: circuit . measure ( 0 , 0 ) QuantumCircuit . measure ( circuit , 0 , 0 )
Bug Fixes¶
-
Fixed an error in the circuit conversion functions
circuit_to_gate()
andcircuit_to_instruction()
(and their associated circuit methodsQuantumCircuit.to_gate()
andQuantumCircuit.to_instruction()
) when acting on a circuit with registerless bits, or bits in more than one register. Previously, the number of bits necessary for the created gate or instruction would be calculated incorrectly, often causing an exception during the conversion.
-
Fixed an issue where calling
QuantumCircuit.copy()
on the "body" circuits of a control-flow operation created with the builder interface would raise an error. For example, this was previously an error, but will now return successfully:from qiskit.circuit import QuantumCircuit , QuantumRegister , ClassicalRegister qreg = QuantumRegister ( 4 ) creg = ClassicalRegister ( 1 ) circ = QuantumCircuit ( qreg , creg ) with circ . if_test (( creg , 0 )): circ . h ( 0 ) if_else_instruction , _ , _ = circ . data [ 0 ] true_body = if_else_instruction . params [ 0 ] true_body . copy ()
-
The control-flow builder interface now supports using
ClassicalRegister
s as conditions in nested control-flow scopes. Previously, doing this would not raise an error immediately, but the internal circuit blocks would not have the correct registers defined, and so later logic that worked with the inner blocks would fail.For example, previously the drawers would fail when trying to draw an inner block conditioned on a classical register, whereas now it will succeed, such as in this example:
from qiskit import QuantumCircuit from qiskit.circuit import QuantumRegister , ClassicalRegister qreg = QuantumRegister ( 4 ) creg = ClassicalRegister ( 1 ) circ = QuantumCircuit ( qreg , creg ) with circ . for_loop ( range ( 10 )) as a : circ . ry ( a , 0 ) with circ . if_test (( creg , 1 )): circ . break_loop () print ( circ . draw ( cregbundle = False )) print ( circ . data [ 0 ][ 0 ] . blocks [ 0 ] . draw ( cregbundle = False ))
-
Fixed
qpy_serialization
support for serializingQuantumCircuit
objects that are usingParameterVector
orParameterVectorElement
as parameters. Previously, aParameterVectorElement
parameter was just treated as aParameter
for QPY serialization which meant theParameterVector
context was lost in QPY and the output order ofparameters
could be incorrect.To fix this issue a new QPY format version, Version 3, was required. This new format version includes a representation of the
ParameterVectorElement
class which is described in theqpy_serialization
documentation at PARAMETER_VECTOR_ELEMENT.
-
Fixed the
qpy_serialization
support for serializing aPauliEvolutionGate
object. Previously, thePauliEvolutionGate
was treated as a custom gate for serialization and would be deserialized as aGate
object that had the same definition and name as the originalPauliEvolutionGate
. However, this would lose the original state from thePauliEvolutionGate
. This has been fixed so that starting in this release aPauliEvolutionGate
in the circuit will be preserved 1:1 across QPY serialization now. The only limitation with this is that it does not support customEvolutionSynthesis
classes. Only the classes available fromqiskit.synthesis
can be used with aPauliEvolutionGate
for qpy serialization.To fix this issue a new QPY format version, Version 3, was required. This new format version includes a representation of the
PauliEvolutionGate
class which is described in theqpy_serialization
documentation at PAULI_EVOLUTION.
-
Two loose functions
qiskit.circuit.measure.measure()
andqiskit.circuit.reset.reset()
were accidentally removed without a deprecation period. They have been reinstated, but are marked as deprecated in favour of the methodsQuantumCircuit.measure()
andQuantumCircuit.reset()
, respectively, and will be removed in a future release.
Other Notes¶
-
The new control-flow builder interface uses various context managers and helper objects to do its work. These should not be considered part of the public API, and are liable to be changed and removed without warning. The usage of the builder interface has stability guarantees, in the sense that the behaviour described by
QuantumCircuit.for_loop()
,while_loop()
andif_test()
for the builder interface are subject to the standard deprecation policies, but the actual objects used to effect this are not. You should not rely on the objects (such asIfContext
orControlFlowBuilderBlock
) existing in their current locations, or having any methods or attributes attached to them.This was not previously clear in the 0.19.0 release. All such objects now have a warning in their documentation strings making this explicit. It is likely in the future that their locations and backing implementations will become quite different.
IBM Q Provider 0.18.2¶
Bug Fixes¶
-
Fix delivered in #1065 for the issue where job kept crashing when
Parameter
was passed in circuit metadata. -
Fix delivered in #1094 for the issue wherein
qiskit.providers.ibmq.runtime.RuntimeEncoder
does an extra decompose() if the circuit being serialized is aBlueprintCircuit
.
Qiskit 0.33.0¶
This release officially marks the end of support for the Qiskit Aqua project in Qiskit. It was originally deprecated in the 0.25.0 release and as was documented in that release the qiskit-aqua
package has been removed from the Qiskit metapackage, which means pip install qiskit
will no longer include qiskit-aqua
. However, because of limitations in python packaging we cannot automatically remove a pre-existing install of qiskit-aqua
when upgrading a previous version of Qiskit to this release (or a future release) with pip install -U qiskit
. If you are upgrading from a previous version it's recommended that you manually uninstall Qiskit Aqua with pip uninstall qiskit-aqua
or install in a fresh python environment.
The application modules that were provided by qiskit-aqua
have been split into several new packages: qiskit-optimization
, qiskit-nature
, qiskit-machine-learning
, and qiskit-finance
. These packages can be installed by themselves (via the standard pip install command, e.g. pip install qiskit-nature
) or with the rest of the Qiskit metapackage as optional extras (e.g. pip install 'qiskit[finance,optimization]'
or pip install 'qiskit[all]'
). The core algorithms and the operator flow now exist as part of Qiskit Terra at qiskit.algorithms
and qiskit.opflow
. Depending on your existing usage of Aqua you should either use the application packages or the new modules in Qiskit Terra. For more details on how to migrate from Qiskit Aqua you can refer to the Aqua Migration Guide.
This release also officially deprecates the Qiskit Ignis project. Accordingly, in a future release the qiskit-ignis
package will be removed from the Qiskit metapackage, which means in that future release pip install qiskit
will no longer include qiskit-ignis
. Qiskit Ignis has been supersceded by the Qiskit Experiments project and active development has ceased. While deprecated, critical bug fixes and compatibility fixes will continue to be made to provide users a sufficient opportunity to migrate off of Ignis. After the deprecation period (which will be no shorter than 3 months from this release) the project will be retired and archived. You can refer to the migration guide for details on how to switch from Qiskit Ignis to Qiskit Experiments.
Terra 0.19.0¶
Prelude¶
The Qiskit Terra 0.19 release highlights are:
-
A new version of the abstract Qiskit/hardware interface, in the form of
BackendV2
, which comes with a new data structureTarget
to allow backends to better model their constraints for the transpiler. -
An extensible plugin interface to the
UnitarySynthesis
transpiler pass, allowing users or other packages to extend Qiskit Terra's synthesis routines with new methods. -
Control-flow instructions, for representing
for
andwhile
loops andif
/else
statements inQuantumCircuit
. The simulators in Qiskit Aer will soon be able to work with these new instructions, allowing you to write more dynamic quantum programs. -
Preliminary support for the evolving OpenQASM 3 specification. You can use the new
qiskit.qasm3
module to serialize yourQuantumCircuit
s into OpenQASM 3, including the new control-flow constructs.
This release marks the end of support for Python 3.6 in Qiskit. This release of Qiskit Terra, and any subsequent bugfix releases in the 0.19.x series, will be the last to work with Python 3.6. Starting from the next minor release (0.20.0) of Qiskit Terra, the minimum required Python version will be 3.7.
As always, there are many more features and fixes in this release as well, which you can read about below.
New Features¶
-
QuantumCircuit.decompose()
and its corresponding transpiler passDecompose
now optionally accept a parameter containing a collection of gate names. If this parameter is given, then only gates with matching names will be decomposed. This supports Unix-shell-style wildcard matches. For example:qc . decompose ([ "h" , "r[xz]" ])
will decompose any
h
,rx
orrz
gates, but leave (for example)x
gates untouched.
-
Added the
termination_checker
argument to theSPSA
optimizer. This allows the user to implement a custom termination criterion.import numpy as np from qiskit.algorithms.optimizers import SPSA def objective ( x ): return np . linalg . norm ( x ) + .04 * np . random . rand ( 1 ) class TerminationChecker : def __init__ ( self , N : int ): """ Callback to terminate optimization when the average decrease over the last N data points is smaller than the specified tolerance. """ self . N = N self . values = [] def __call__ ( self , nfev , parameters , value , stepsize , accepted ) -> bool : """ Returns: True if the optimization loop should be terminated. """ self . values . append ( value ) if len ( self . values ) > self . N : last_values = self . values [ - self . N :] pp = np . polyfit ( range ( self . N ), last_values , 1 ) slope = pp [ 0 ] / self . N if slope > 0 : return True return False maxiter = 400 spsa = SPSA ( maxiter = maxiter , termination_checker = TerminationChecker ( 10 )) parameters , value , niter = spsa . optimize ( 2 , objective , initial_point = np . array ([ 0.5 , 0.5 ]))
-
Added a new version of the
Backend
interface,BackendV2
. This new version is a large change from the previous version,BackendV1
and changes both the user access pattern for properties of the backend (like number of qubits, etc) and how the backend represents its constraints to the transpiler. The execution of circuits (via therun()
method) remains unchanged. With aBackendV2
backend instead of having a separateconfiguration()
,properties()
, anddefaults()
methods that constructBackendConfiguration
,BackendProperties
, andPulseDefaults
objects respectively, like in theBackendV1
interface, the attributes contained in those output objects are accessible directly as attributes of theBackendV2
object. For example, to get the number of qubits for a backend withBackendV1
you would do:num_qubits = backend . configuration () . n_qubits
while with
BackendV2
it is:num_qubits = backend . num_qubits
The other change around this is that the number of attributes exposed in the abstract
BackendV2
class is designed to be a hardware/vendor agnostic set of the required or optional fields that the rest of Qiskit can use today with any backend. Subclasses of the abstractBackendV2
class can add support for additional attributes and methods beyond those defined inBackendV2
, but these will not be supported universally throughout Qiskit.The other critical change that is primarily important for provider authors is how a
BackendV2
exposes the properties of a particular backend to the transpiler. WithBackendV2
this is done via aTarget
object. TheTarget
, which is exposed via thetarget
attribute, is used to represent the set of constraints for running circuits on a particular backend. It contains the subset of information previously exposed by theBackendConfiguration
,BackendProperties
, andPulseDefaults
classes which the transpiler can actively use. When migrating a provider to useBackendV2
(or when creating a new provider package) the construction of backend objects will primarily be around creating aTarget
object for the backend.
-
Added a new
Target
class to thetranspiler
module. TheTarget
class is designed to represent the constraints of backend to the compiler. TheTarget
class is intended to be used with aBackendV2
backend and is how backends will model their constraints for the transpiler moving forward. It combines the previously distinct fields used for controlling thetranspile()
target device (e.g.basis_gates
,coupling_map
,instruction_durations
, etc) into a single data structure. It also adds additional functionality on top of what was available previously such as representing heterogeneous gate sets, multi-qubit gate connectivity, and tuned variants of the same gates. Currently the transpiler doesn't factor in all these constraints, but over time it will grow to leverage the extra functionality.
-
The
Options
class now has optional support for specifying validators. This enablesBackend
authors to optionally specify basic validation on the user supplied values for fields in theOptions
object. For example, if you had anOptions
object defined with:from qiskit.providers.Options options = Options ( shots = 1024 )
you can set a validator on shots for it to be between 1 and 4096 with:
options . set_validator ( 'shots' , ( 1 , 4096 ))
With the validator set any call to the
update_options()
method will check that ifshots
is being updated the proposed new value is within the valid range.
-
Added a new transpiler analysis pass,
ContainsInstruction
, to theqiskit.transpiler.passes
module. This pass is used to determine if a circuit contains a specific instruction. It takes in a single parameter at initialization, the name of the instruction to check for and set a boolean in the property set whether the circuit contains that instruction or not. For example:from qiskit.transpiler.passes import ContainsInstruction from qiskit.circuit import QuantumCircuit circuit = QuantumCircuit ( 2 ) circuit . h ( 0 ) circuit . cx ( 0 , 1 ) circuit . measure_all () property_set = {} # Contains Hadamard contains_h = ContainsInstruction ( "h" ) contains_h ( circuit , property_set ) assert property_set [ "contains_h" ] == True # Not contains SX contains_sx = ContainsInstruction ( "sx" ) contains_sx ( circuit , property_set ) assert property_set [ "contains_sx" ] == False
-
Added a utility function
qiskit.utils.detach_prefix()
that is a counterpart ofapply_prefix()
. The new function returns a tuple of scaled value and prefix from a given float value. For example, a value1.3e8
will be converted into(130, "M")
that can be used to display a value in the user friendly format, such as130 MHz
.
-
The values
"gate_error"
and"balanced"
are now available for theobjective
option in the construction of theBIPMapping
object, and"balanced"
is now the default.The
"gate_error"
objective requires passing aBackendProperties
instance in thebackend_prop
kwarg, which contains the 2q-gate gate errors used in the computation of the objectives. The"balanced"
objective will use theBackendProperties
instance if it is given, but otherwise will assume a CX error rate as given in the new parameterdefault_cx_error_rate
. The relative weights of the gate-error and depth components of the balanced objective can be controlled with the newdepth_obj_weight
parameter.
-
Every attribute of the
VQE
class that is set at the initialization is now accessible with getters and setters. Further, the default values of the VQE attributesansatz
andoptimizer
can be reset by assigningNone
to them:vqe = VQE ( my_ansatz , my_optimizer ) vqe . ansatz = None # reset to default: RealAmplitudes ansatz vqe . optimizer = None # reset to default: SLSQP optimizer
-
Added a new method
PauliList.group_qubit_wise_commuting()
that partitions aPauliList
into sets of mutually qubit-wise commutingPauli
operators. For example:from qiskit.quantum_info import PauliList , Pauli pauli_list = PauliList ([ Pauli ( "IY" ), Pauli ( "XX" ), Pauli ( "YY" ), Pauli ( "YX" )]) pauli_list . group_qubit_wise_commuting ()
-
Added a new coupling-map constructor method
CouplingMap.from_hexagonal_lattice()
for constructing a hexagonal lattice coupling map. For example, to construct a 2x2 hexagonal lattice coupling map:from qiskit.transpiler import CouplingMap cmap = CouplingMap . from_hexagonal_lattice ( 2 , 2 ) cmap . draw ()
-
New fake backend classes are available under
qiskit.test.mock
. These include mocked versions ofibmq_brooklyn
,ibmq_manila
,ibmq_jakarta
, andibmq_lagos
. As with the other fake backends, these include snapshots of calibration data (i.e.backend.defaults()
) and error data (i.e.backend.properties()
) taken from the real system, and can be used for local testing, compilation and simulation.
-
Added the
OperatorBase.is_hermitian()
method to check whether the operator is Hermitian or not.NumPyEigensolver
andNumPyMinimumEigensolver
useeigh
oreigsh
to solve the eigenvalue problem when the operator is Hermitian.
-
Added a new constructor method
PassManagerConfig.from_backend()
. It constructs aPassManagerConfig
object with user options and the configuration of a backend. With this feature, a preset passmanager can be built easier. For example:from qiskit.transpiler.passmanager_config import PassManagerConfig from qiskit.transpiler.preset_passmanagers import level_1_pass_manager from qiskit.test.mock import FakeMelbourne pass_manager = level_1_pass_manager ( PassManagerConfig . from_backend ( FakeMelbourne (), seed_transpiler = 42 ) )
-
A new transpiler pass,
PulseGates
, was added, which automatically extracts user-provided calibrations from the instruction schedule map and attaches the gate schedule to the given (transpiled) quantum circuit as a pulse gate.The
PulseGates
transpiler pass is applied to all optimization levels from 0 to 3. No gate implementation is updated unless the end-user explicitly overrides thebackend.defaults().instruction_schedule_map
. This pass saves users from individually callingQuantumCircuit.add_calibration()
for every circuit run on the hardware.To supplement this new pass, a schedule was added to
InstructionScheduleMap
and is implicitly updated with a metadata field"publisher"
. Backend-calibrated gate schedules have a special publisher kind to avoid overriding circuits with calibrations of already known schedules. Usually, end-users don't need to take care of this metadata as it is applied automatically. You can callInstructionScheduleMap.has_custom_gate()
to check if the map has custom gate calibration.See the below code example to learn how to apply custom gate implementation for all circuits under execution.
from qiskit.test.mock import FakeGuadalupe from qiskit import pulse , circuit , transpile backend = FakeGuadalupe () with pulse . build ( backend , name = "x" ) as x_q0 : pulse . play ( pulse . Constant ( 160 , 0.1 ), pulse . drive_channel ( 0 )) backend . defaults () . instruction_schedule_map . add ( "x" , ( 0 ,), x_q0 ) circs = [] for _ in range ( 100 ): circ = circuit . QuantumCircuit ( 1 ) circ . sx ( 0 ) circ . rz ( 1.57 , 0 ) circ . x ( 0 ) circ . measure_active () circs . append ( circ ) circs = transpile ( circs , backend ) circs [ 0 ] . calibrations # This returns calibration only for x gate
Note that the instruction schedule map is a mutable object. If you override one of the entries and use that backend for other experiments, you may accidentally update the gate definition.
backend = FakeGuadalupe () instmap = backend . defaults () . instruction_schedule_map instmap . add ( "x" , ( 0 , ), my_x_gate_schedule ) qc = QuantumCircuit ( 1 , 1 ) qc . x ( 0 ) qc . measure ( 0 , 0 ) qc = transpile ( qc , backend ) # This backend uses custom X gate
If you want to update the gate definitions of a specific experiment, you need to first deepcopy the instruction schedule map and directly pass it to the transpiler.
-
Introduced a new option
qubit_subset
to the constructor ofBIPMapping
. The option enables us to specify physical qubits to be used (incoupling_map
of the device) during the mapping in one line:mapped_circ = BIPMapping ( coupling_map = CouplingMap ([[ 0 , 1 ], [ 1 , 2 ], [ 1 , 3 ], [ 3 , 4 ]]), qubit_subset = [ 1 , 3 , 4 ] )( circ )
Previously, to do the same thing, we had to supply a reduced
coupling_map
which contains only the qubits to be used, embed the resulting circuit onto the originalcoupling_map
and update theQuantumCircuit._layout
accordingly:reduced_coupling = coupling_map . reduce ( qubit_to_use ) mapped = BIPMapping ( reduced_coupling )( circ ) # skip the definition of fill_with_ancilla() # recover circuit on original coupling map layout = Layout ({ q : qubit_to_use [ i ] for i , q in enumerate ( mapped . qubits )}) for reg in mapped . qregs : layout . add_register ( reg ) property_set = { "layout" : fill_with_ancilla ( layout )} recovered = ApplyLayout ()( mapped , property_set ) # recover layout overall_layout = Layout ({ v : qubit_to_use [ q ] for v , q in mapped . _layout . get_virtual_bits () . items ()}) for reg in mapped . qregs : overall_layout . add_register ( reg ) recovered . _layout = fill_with_ancilla ( overall_layout )
-
Added the
ignore_pauli_phase
andcopy
arguments to the constructor ofSparsePauliOp
.ignore_pauli_phase
prevents thephase
attribute of an inputPauliList
from being read, which is more performant if thePauliList
is already known to have all phases as zero in the internal ZX convention.copy
allows users to avoid the copy of the input data when they explicitly setcopy=False
.
-
Improved performance of the following
SparsePauliOp
operations:-
simplify()
(see #7122) -
compose()
(see #7126) -
_add()
(see #7138) -
from_list()
and__init__()
(see other discussion in #7138).
-
-
Added the
SparsePauliOp.sum()
method to add together manySparsePauliOp
s. This method has significantly better performance than adding the instances together in a loop. For example, the previous way to add severalSparsePauliOp
s together would be to do:from qiskit.quantum_info import SparsePauliOp , random_pauli_list sparse_ops = [ SparsePauliOp ( random_pauli_list ( 10 , 10 )) for _ in [ None ] * 1000 ] total = sparse_ops [ 0 ] for op in sparse_ops [ 1 :]: total += op
This can now be done far more efficiently (in both speed and typing!) as:
SparsePauliOp . sum ( sparse_ops )
-
Added an argument
limit_amplitude
to the constructor ofParametricPulse
, which is the base class ofGaussian
,GaussianSquare
,Drag
andConstant
, to allowing disabling the amplitude limit of 1 on a pulse-by-pulse basis. Withlimit_amplitude=False
, individual pulses may have an amplitude exceeding unity without raising aPulseError
. See #6544 for more detail.
-
Using
QuantumCircuit.draw()
orcircuit_drawer()
with thelatex
drawer will now generate a file in an image format inferred from the filename extension, for example:import qiskit circuit = qiskit . QuantumCircuit ( 2 ) circuit . h ( 0 ) circuit . cx ( 0 , 1 ) circuit . draw ( 'latex' , filename = './file.jpg' )
This will save the circuit drawing in the JPEG format. Previously, the image always be in PNG format. Refer to #6448 for more details.
Now, if it encounters a filename extension which is not supported, for example:
circuit . draw ( 'latex' , filename = './file.spooky' )
it will raise a
ValueError
to change the filename extension to a supported image format.
-
Added the parameter
filename
toplot_gate_map()
andplot_coupling_map()
, which allows saving the resulting images to a file.
-
Introduced an approximate quantum compiler and a corresponding unitary synthesis plugin implementation. The main AQC class is
AQC
for a standalone version that compiles a unitary matrix into an approximate circuit. The plugin may be invoked bytranspile()
when theunitary_synthesis_method
argument is set to'aqc'
. Seeqiskit.transpiler.synthesis.aqc
for full details.
-
Added a
filter_function
argument toQuantumCircuit.depth()
andQuantumCircuit.size()
in order to analyze circuit operations according to some criteria.For example, to get the number of two-qubit gates, you can do:
circuit . size ( lambda x : x [ 0 ] . num_qubits == 2 )
Or to get the depth of T gates acting on the zeroth qubit:
circuit . depth ( lambda x : x [ 0 ] . name == 't' and circuit . qubits [ 0 ] in x [ 1 ])
-
Added a new transpiler pass,
CollectMultiQBlocks
, to theqiskit.transpiler.passes
module. This pass is used to collect sequences of uninterrupted gates acting on groups of qubits. It provides a similar function to the existingCollect2qBlocks
pass, but while that pass is designed and optimized to find 2 qubit blocks this new pass will work to find blocks of any size.
-
There is a builder interface for the new control-flow operations on
QuantumCircuit
, such as the newForLoopOp
,IfElseOp
, andWhileLoopOp
. The interface uses the same circuit methods, i.e.QuantumCircuit.for_loop()
,QuantumCircuit.if_test()
andQuantumCircuit.while_loop()
, which are overloaded so that if thebody
parameter is not given, they return a context manager. Entering one of these context managers pushes a scope into the circuit, and captures all gate calls (and other scopes) and the resources these use, and builds up the relevant operation at the end. For example, you can now do:qc = QuantumCircuit ( 2 , 2 ) with qc . for_loop ( range ( 5 )) as i : qc . rx ( i * math . pi / 4 , 0 )
This will produce a
ForLoopOp
onqc
, which knows that qubit 0 is the only resource used within the loop body. These context managers can be nested, and will correctly determine their widths. You can useQuantumCircuit.break_loop()
andQuantumCircuit.continue_loop()
within a context, and it will expand to be the correct width for its containing loop, even if it is nested in furtherQuantumCircuit.if_test()
blocks.The
if_test()
context manager provides a chained manager which, if desired, can be used to create anelse
block, such as by:qreg = QuantumRegister ( 2 ) creg = ClassicalRegister ( 2 ) qc = QuantumCircuit ( qreg , creg ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc . measure ( 0 , 0 ) with qc . if_test (( creg , 0 )) as else_ : qc . x ( 1 ) with else_ : qc . z ( 1 )
The manager will ensure that the
if
andelse
bodies are defined over the same set of resources.
-
Introduced a new transpiler pass
InverseCancellation
that generalizes theCXCancellation
pass to cancel any self-inverse gates or gate-inverse pairs. It can be used by initializingInverseCancellation
and passing a gate to cancel, for example:from qiskit.transpiler.passes import InverseCancellation from qiskit import QuantumCircuit from qiskit.circuit.library import HGate from qiskit.transpiler import PassManager qc = QuantumCircuit ( 2 , 2 ) qc . h ( 0 ) qc . h ( 0 ) pass_ = InverseCancellation ([ HGate ()]) pm = PassManager ( pass_ ) new_circ = pm . run ( qc )
-
The constructor of
RZXCalibrationBuilder
has two new kwargsinstruction_schedule_map
andqubit_channel_mapping
which take aInstructionScheduleMap
and list of channel name lists for each qubit respectively. These new arguments are used to directly specify the information needed from a backend target. They should be used instead of passing aBaseBackend
orBackendV1
object directly to the pass with thebackend
argument.
-
The
Statevector
s of states comprised only of qubits can now be drawn in LaTeX in ket notation. In ket notation the entries of the statevector are processed such that exact factors like fractions or square roots of two are drawn as such. The particular convention can be chosen by passing theconvention
keyword argument as either"ket"
or"vector"
as appropriate:import math from qiskit.quantum_info import Statevector sv = Statevector ([ math . sqrt ( 0.5 ), 0 , 0 , - math . sqrt ( 0.5 )]) sv . draw ( "latex" , convention = "ket" ) sv . draw ( "latex" , convention = "vector" )
-
Added a new transpiler pass
EchoRZXWeylDecomposition
that allows users to decompose an arbitrary two-qubit gate in terms of echoed RZX-gates by leveraging Cartan's decomposition. In combination with other transpiler passes, this can be used to transpile arbitrary circuits to RZX-gate-based and pulse-efficient circuits that implement the same unitary.
-
The
SPSA
andQNSPSA
optimizer classes are now capable of batching as many circuit evaluations as possible for both the iterations and the initial calibrations. This can be leveraged by setting themax_evals_grouped
kwarg on the constructor forVQE
when using eitherSPSA
orQNSPSA
as theoptimizer
parameter. For example:from qiskit.circuit.library import TwoLocal from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import QNSPSA from qiskit.test.mock import FakeMontreal backend = FakeMontreal () ansatz = TwoLocal ( 2 , rotation_blocks = [ "ry" , "rz" ], entanglement_blocks = "cz" ) qnspsa = QNSPSA ( fidelity , maxiter = 5 ) vqe = VQE ( ansatz = ansatz , optimizer = qnspsa , max_evals_grouped = 100 , quantum_instance = backend , )
-
This release introduces a decomposition method for two-qubit gates which targets user-defined sets of RZX gates. Transpiler users can enable decomposition for {
RZX(pi/2)
,RZX(pi/4)
, andRZX(pi/6)
} specifically by including'rzx'
in theirbasis_gates
list when callingtranspile()
. Quantum information package users can find the method itself under theXXDecomposer
class.
-
Added a transpiler pass
Optimize1qGatesSimpleCommutation
, which optimizes a circuit according to a strategy of commuting single-qubit gates around to discover resynthesis opportunities.
-
Added a
max_job_tries
parameter toQuantumInstance
, to limit the number of times a job will attempt to be executed on a backend. Previously the submission and fetching of results would be attempted infinitely, even if the job was cancelled or errored on the backend. The default is now 50, and the previous behaviour can be achieved by settingmax_job_tries=-1
. Fixes #6872 and #6821.
-
The
latex
output method for thecircuit_drawer()
function and theQuantumCircuit.draw()
method can now draw circuits that contain gates with single bit condition. This was added for compatibility of latex drawer with the new feature of supporting classical conditioning of gates on single classical bits.
-
The
"mpl"
output method for thecircuit_drawer()
function and theQuantumCircuit.draw()
method can now draw circuits that contain gates with single bit condition. This was added for compatibility of the"mpl"
drawer with the new feature of supporting classical conditioning of gates on single classical bits.
-
The
text
output method for thecircuit_drawer()
function and theQuantumCircuit.draw()
method can now draw circuits that contain gates with single bit condition. This was added for compatibility of text drawer with the new feature of supporting classical conditioning of gates on single classical bits.
-
A new analysis transpiler pass,
GatesInBasis
, was added toqiskit.transpiler.passes
. This pass is used to check if theDAGCircuit
being transpiled has all the gates in the configured basis set or not. It will set the attribute"all_gates_in_basis"
in the property set toTrue
if all the gates in theDAGCircuit
are in the configured basis set orFalse
if they are not. For example:from qiskit.circuit import QuantumCircuit from qiskit.transpiler.passes import GatesInBasis # Instatiate Pass basis_gates = [ "cx" , "h" ] basis_check_pass = GatesInBasis ( basis_gates ) # Build circuit circuit = QuantumCircuit ( 2 ) circuit . h ( 0 ) circuit . cx ( 0 , 1 ) circuit . measure_all () # Run pass on circuit property_set = {} basis_check_pass ( circuit , property_set = property_set ) assert property_set [ "all_gates_in_basis" ]
-
Added two new constructor methods,
from_heavy_hex()
andfrom_heavy_square()
, to theCouplingMap
class. These constructor methods are used to create aCouplingMap
that are a heavy hex or heavy square graph as described in Chamberland et al., 2020.For example:
from qiskit.transpiler import CouplingMap cmap = CouplingMap . from_heavy_hex ( 5 ) cmap . draw ()
from qiskit.transpiler import CouplingMap cmap = CouplingMap . from_heavy_square ( 5 ) cmap . draw ()
-
The
HHL
algorithm can now find solutions when its matrix has negative eigenvalues. To enable this, the algorithm now adds an extra qubit to represent the sign of the value, and the helper algorithmExactReciprocal
was updated to process this new information. See #6971 for more details.
-
Added two new classes,
CompleteMeasFitter
andTensoredMeasFitter
to theqiskit.utils.mitigation
module. These classes are for use only as values for themeasurement_error_mitigation_cls
kwarg of theQuantumInstance
class. The instantiation and usage of these classes (or anything else inqiskit.utils.mitigation
) outside of themeasurement_error_mitigation_cls
kwarg should be treated as an internal private API and not relied upon.
-
The
ListOp
class inqiskit.opflow
now has acoeffs
attribute, which returns a list of the coefficients of the operator list, with the overall coefficient (ListOp.coeff
) distributed multiplicatively into the list. Note thatListOp
objects may be nested (contained inoplist
of aListOp
object), and in these cases an exception is raised if the coeffs method is called. TheListOp.coeffs
method conveniently duck-types against thecoeffs
property method of the non-nestingPauliSumOp
class.
-
The
Statevector
class is now subscriptable. User can now retrieve the nth coefficient in aStatevector
by index asstatevec[n]
.
-
Added the
Statevector.inner
method to calculate inner products ofStatevector
instances. For example:statevec_inner_other = statevec . inner ( other )
will return the inner product of
statevec
withother
. Whilestatevec
must be aStatevector
,other
can be anything that can be constructed into aStatevector
, such as a Numpy array.
-
Added a new parameter,
add_bits
, toQuantumCircuit.measure_all()
. By default it is set toTrue
to maintain the previous behaviour of adding a newClassicalRegister
of the same size as the number of qubits to store the measurements. If set toFalse
, the measurements will be stored in the already existing classical bits. For example, if you created a circuit with existing classical bits like:from qiskit.circuit import QuantumCircuit , QuantumRegister , ClassicalRegister qr = QuantumRegister ( 2 ) cr = ClassicalRegister ( 2 , "meas" ) circuit = QuantumCircuit ( qr , cr )
calling
circuit.measure_all(add_bits=False)
will use the existing classical registercr
as the output target of theMeasurement
objects added to the circuit.
-
ParameterExpression
now delegates its numeric conversions to the underlying symbolic library, even if there are potentially unbound parameters. This allows conversions of expressions such as:>>> from qiskit.circuit import Parameter >>> x = Parameter ( 'x' ) >>> float ( x - x + 2.3 ) 2.3
where the underlying expression has a fixed value, but the parameter
x
is not yet bound.
-
Added an
Optimizer.minimize()
method to all optimizers:Optimizer
and derived classes. This method mimics the signature of SciPy'sminimize()
function and returns anOptimizerResult
.For example
import numpy as np from qiskit.algorithms.optimizers import COBYLA def loss ( x ): return - ( x [ 0 ] - 1 ) ** 2 - ( x [ 1 ] + 1 ) ** 3 initial_point = np . array ([ 0 , 0 ]) optimizer = COBYLA () result = optimizer . minimize ( loss , initial_point ) optimal_parameters = result . x minimum_value = result . fun num_function_evals = result . nfev
-
Added a
PauliEvolutionGate
to the circuit library (qiskit.circuit.library
) which defines a gate performing time evolution of (sums or sums-of-sums of)Pauli
s. The synthesis of this gate is performed byEvolutionSynthesis
and is decoupled from the gate itself. Currently available synthesis methods are:-
LieTrotter
: first order Trotterization -
SuzukiTrotter
: higher order Trotterization -
MatrixExponential
: exact, matrix-based evolution
For example:
from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import PauliEvolutionGate from qiskit.quantum_info import SparsePauliOp from qiskit.synthesis import SuzukiTrotter operator = SparsePauliOp . from_list ([ ( "XIZ" , 0.5 ), ( "ZZX" , 0.5 ), ( "IYY" , - 1 ) ]) time = 0.12 # evolution time synth = SuzukiTrotter ( order = 4 , reps = 2 ) evo = PauliEvolutionGate ( operator , time = time , synthesis = synth ) circuit = QuantumCircuit ( 3 ) circuit . append ( evo , range ( 3 ))
-
-
A new function
plot_coupling_map()
has been introduced, which extends the functionality of the existing functionplot_gate_map()
, by accepting three parameters:num_qubit
,qubit_coordinates
, andcoupling_map
(instead ofbackend
), to allow an arbitrary qubit coupling map to be plotted.
-
Qiskit Terra now has initial support for serializing
QuantumCircuit
s to OpenQASM 3:from qiskit.circuit import QuantumCircuit , QuantumRegister , ClassicalRegister from qiskit import qasm3 qc = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) print ( qasm3 . dumps ( qc ))
OPENQASM 3; include "stdgates.inc"; qubit[2] _all_qubits; let q = _all_qubits[0:1]; h q[0]; cx q[0], q[1];
This initial release has limited support for named registers, basic built-in instructions (such as measure, barrier and reset), user-defined gates, user-defined instructions (as subroutines), and the new control-flow constructs also introduced in this release:
from qiskit.circuit import QuantumCircuit , QuantumRegister , ClassicalRegister from qiskit import qasm3 import math composite_circ_qreg = QuantumRegister ( 2 ) composite_circ = QuantumCircuit ( composite_circ_qreg , name = "composite_circ" ) composite_circ . h ( 0 ) composite_circ . x ( 1 ) composite_circ . cx ( 0 , 1 ) composite_circ_gate = composite_circ . to_gate () qr = QuantumRegister ( 2 , "qr" ) cr = ClassicalRegister ( 2 , "cr" ) qc = QuantumCircuit ( qr , cr ) with qc . for_loop ( range ( 4 )) as i : qc . rx ( i * math . pi / 4 , 0 ) qc . cx ( 0 , 1 ) qc . barrier () qc . append ( composite_circ_gate , [ 0 , 1 ]) qc . measure ([ 0 , 1 ], [ 0 , 1 ]) print ( qasm3 . dumps ( qc ))
OPENQASM 3; include "stdgates.inc"; gate composite_circ _gate_q_0, _gate_q_1 { h _gate_q_0; x _gate_q_1; cx _gate_q_0, _gate_q_1; } bit[2] cr; qubit[2] _all_qubits; let qr = _all_qubits[0:1]; for _loop_i_0 in [0:3] { rx(pi/4*_loop_i_0) qr[0]; cx qr[0], qr[1]; } barrier qr[0], qr[1]; composite_circ qr[0], qr[1]; cr[0] = measure qr[0]; cr[1] = measure qr[1];
-
The
QDrift
class was reformulated as a synthesis method forPauliEvolutionGate
, deriving fromTrotterizationBase
.from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import PauliEvolutionGate from qiskit.synthesis import QDrift from qiskit.opflow import X , Y , Z qdrift = QDrift ( reps = 2 ) operator = ( X ^ 3 ) + ( Y ^ 3 ) + ( Z ^ 3 ) time = 2.345 # evolution time evolution_gate = PauliEvolutionGate ( operator , time , synthesis = qdrift ) circuit = QuantumCircuit ( 3 ) circuit . append ( evolution_gate , range ( 3 ))
-
QPY serialization is now capable of representing
global_phase
attributes of aQuantumCircuit
object that are anint
,Parameter
object, orParameterExpression
object. Previous versions of QPY would only accept aglobal_phase
that was afloat
.This requires the QPY format Version 2 which was introduced in this release to represent the additional types.
-
A new
find_bit()
method has been added to theQuantumCircuit
class, which allows lookups of the index and registers of a providedBit
on the given circuit. The method returns a two-elementnamedtuple
containing 0) the index of theBit
in eitherqubits
(for aQubit
) orclbits
(for aClbit
) and 1) a list of length-2 tuples containing each circuitRegister
which contains theBit
, and the index in thatRegister
at which theBit
can be found.For example:
from qiskit.circuit import QuantumCircuit , QuantumRegister , Qubit reg1 = QuantumRegister ( 3 , 'foo' ) qubit = Qubit () reg2 = QuantumRegister ( 2 , 'bar' ) qc = QuantumCircuit ( reg1 , [ qubit ], reg2 ) print ( qc . find_bit ( reg1 [ 2 ])) print ( qc . find_bit ( qubit ))
would generate:
BitLocations ( index = 2 , registers = [( QuantumRegister ( 3 , 'foo' ), 2 )]) BitLocations ( index = 3 , registers = [])
-
Three new
Instruction
subclasses have been added to support control flow operations in dynamic circuits:WhileLoopOp
,ForLoopOp
, andIfElseOp
. Additionally, two subclasses,BreakLoopOp
, andContinueLoopOp
, have been added to support breaking from and continuing to the next iteration of a loop context, respectively.These can be created as stand-alone
Instruction
s, or appended to an existingQuantumCircuit
instance via their respective methods,QuantumCircuit.while_loop()
,for_loop()
,if_test()
,if_else()
,break_loop()
, andcontinue_loop()
.
-
Added the
BaseReadoutMitigator
abstract base class for implementing classical measurement error mitigators. These objects are intended for mitigation measurement errors inCounts
objects returned from execution of circuits on backends with measurement errors.Readout mitigator classes have two main methods:
-
expectation_value()
which computes an mitigated expectation value and standard error of a diagonal operator from a noisyCounts
object. -
quasi_probabilities()
that computes an error mitigatedQuasiDistribution
, including standard error, from a noisy counts object.
Note that currently the
qiskit.algorithms
module and theQuantumInstance
class still use the legacy mitigators migrated from Qiskit Ignis inqiskit.utils.mitigation
. It is planned to upgrade the module to use the new mitigator classes and deprecate the legacy mitgation code in a future release. -
-
Added the
LocalReadoutMitigator
class for performing measurement readout error mitigation of local measurement errors. Local measuerment errors are those that are described by a tensor-product of single-qubit measurement errors.This class can be initialized with a list of \(N\) single-qubit of measurement error assignment matrices or from a backend using the readout error information in the backend properties.
Mitigation is implemented using local assignment-matrix inversion which has complexity of \(O(2^N)\) for \(N\)-qubit mitigation of
QuasiDistribution
and expectation values.
-
Added the
CorrelatedReadoutMitigator
class for performing measurement readout error mitigation of correlated measurement errors. This class can be initialized with a single \(2^N \times 2^N\) measurement error assignment matrix that descirbes the error probabilities. Mitigation is implemented via inversion of assigment matrix which has mitigation complexity of \(O(4^N)\) ofQuasiDistribution
and expectation values.
-
Added a
QuasiDistribution.stddev_upper_bound
attribute and a kwarg to the constructor of theQuasiDistribution
class, which is used for storing standard errors in quasi-probability estimates. This is used byBaseReadoutMitigator
classes to store the standard error in mitigated quasi probabilities.
-
Added a
shots()
method toqiskit.result.Counts
to return the sum of all outcomes in the counts.
-
When running the
Grover
algorithm class if the optimal power is known and only a single circuit is run, theAmplificationProblem.is_good_state
callback function is no longer required to be set and the Grover search will return the most likely bitstring. Generally, if the optimal power of the Grover operator is not known, theGrover
algorithm checks different powers (i.e. iterations) and applies theis_good_state
function to check whether a good bitstring has been measured. For example, you are now able to run something like:from qiskit.algorithms import Grover , AmplificationProblem from qiskit.providers.aer import AerSimulator from qiskit.quantum_info import Statevector # Fixed Grover power: 2. grover = Grover ( iterations = 2 , quantum_instance = AerSimulator ()) # The ``is_good_state`` argument not required here since Grover search # will be run only once, with a power of 2. problem = AmplificationProblem ( Statevector . from_label ( "111" )) # Run Grover search and print the best measurement result = grover . amplify ( problem ) print ( result . top_measurement ) # should print 111
-
Added method
remove_cregs()
to classDAGCircuit
to support classical register removal.
-
Added method
remove_clbits()
to classDAGCircuit
to support the removal of idle classical bits. Any classical registers referencing a removed bit are also removed.
-
Added a new method,
replace_block_with_op()
, to theDAGCircuit
class. This method is used to replace a block of nodes in the DAG with a single operation. The canonical example is for theConsolidateBlocks
pass which replaces blocks of nodes with equivalentUnitaryGate
nodes.
-
Added a new analysis transpiler pass,
Collect1qRuns
, to theqiskit.transpiler.passes
module. This pass is used to find sequences of uninterrupted gates acting on a single qubit. It is similar to theCollect2qBlocks
andCollectMultiQBlocks
but optimized for single qubit runs instead of multiple qubit blocks.
-
Various transpilation internals now use new features in retworkx 0.10 when operating on the internal circuit representation. This can often result in speedups in calls to
transpile
of around 10-40%, with greater effects at higher optimization levels. See #6302 for more details.
-
The
UnitarySynthesis
transpiler pass inqiskit.transpiler.passes
has a new kwarg in the constructor,min_qubits
. When specified this can be set to anint
value which is the minimum sizeUnitaryGate
object to run the unitary synthesis on. If aUnitaryGate
in aQuantumCircuit
uses fewer qubits it will be skipped by that instance of the pass.
-
The
Eigensolver
andMinimumEigensolver
interfaces now support the typeDict[str, Optional[OperatorBase]]
for theaux_operators
parameter in their respectivecompute_eigenvalues()
andcompute_minimum_eigenvalue()
methods. In this case, the auxiliary eigenvalues are also stored in a dictionary under the same keys provided by theaux_operators
dictionary. Keys that correspond to an operator that does not commute with the main operator are dropped.
-
The
BasisTranslator
,GateDirection
, andCheckGateDirection
transpiler passes have a newtarget
kwarg in their constructors, which can be used to set aTarget
object as the target for the pass. If it is set it will be used instead of thetarget_basis
(in the case of theBasisTranslator
pass) orcoupling_map
(in the case of theGateDirection
andCheckGateDirection
passes) arguments.
-
Allow two transpiler stages in the
QuantumInstance
, one for parameterized circuits and a second one for bound circuits (i.e. no free parameters) only. If a quantum instance with passes for unbound and bound circuits is passed into aCircuitSampler
, the sampler will attempt to apply the unbound pass once on the parameterized circuit, cache it, and only apply the bound pass for all future evaluations.This enables variational algorithms like the
VQE
to run a custom pass manager for parameterized circuits once and, additionally, another the transpiler again with a different custom pass manager on the bound circuits in each iteration. Being able to run different pass managers is important because not all passes support parameterized circuits (for exampleOptimize1qGatesDecomposition
only works with bound circuit parameters).For example, this feature allows using the pulse-efficient CX decomposition in the VQE, as
from qiskit.algorithms import VQE from qiskit.opflow import Z from qiskit.circuit.library.standard_gates.equivalence_library import StandardEquivalenceLibrary as std_eqlib from qiskit.transpiler import PassManager , PassManagerConfig , CouplingMap from qiskit.transpiler.preset_passmanagers import level_1_pass_manager from qiskit.transpiler.passes import ( Collect2qBlocks , ConsolidateBlocks , Optimize1qGatesDecomposition , RZXCalibrationBuilderNoEcho , UnrollCustomDefinitions , BasisTranslator ) from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import EchoRZXWeylDecomposition from qiskit.test.mock import FakeBelem from qiskit.utils import QuantumInstance # Replace by a real backend! If not ensure qiskit-aer is installed to simulate the backend backend = FakeBelem () # Build the pass manager for the parameterized circuit rzx_basis = [ 'rzx' , 'rz' , 'x' , 'sx' ] coupling_map = CouplingMap ( backend . configuration () . coupling_map ) config = PassManagerConfig ( basis_gates = rzx_basis , coupling_map = coupling_map ) pre = level_1_pass_manager ( config ) # Build a pass manager for the CX decomposition (works only on bound circuits) post = PassManager ([ # Consolidate consecutive two-qubit operations. Collect2qBlocks (), ConsolidateBlocks ( basis_gates = [ 'rz' , 'sx' , 'x' , 'rxx' ]), # Rewrite circuit in terms of Weyl-decomposed echoed RZX gates. EchoRZXWeylDecomposition ( backend ), # Attach scaled CR pulse schedules to the RZX gates. RZXCalibrationBuilderNoEcho ( backend ), # Simplify single-qubit gates. UnrollCustomDefinitions ( std_eqlib , rzx_basis ), BasisTranslator ( std_eqlib , rzx_basis ), Optimize1qGatesDecomposition ( rzx_basis ), ]) quantum_instance = QuantumInstance ( backend , pass_manager = pre , bound_pass_manager = post ) vqe = VQE ( quantum_instance = quantum_instance ) result = vqe . compute_minimum_eigenvalue ( Z ^ Z )
-
Introduced a new unitary synthesis plugin interface which is used to enable using alternative synthesis techniques included in external packages seamlessly with the
UnitarySynthesis
transpiler pass. Users can select a plugin to use when callingtranspile()
by setting theunitary_synthesis_method
kwarg to the plugin's name. A full list of installed plugins can be found using theqiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names()
function. For example, if you installed a package that includes a synthesis plugin namedspecial_synth
you could use it with:from qiskit import transpile transpile ( qc , unitary_synthesis_method = 'special_synth' , optimization_level = 3 )
This will replace all uses of the
UnitarySynthesis
with the method included in the external package that exports thespecial_synth
plugin.The plugin interface is built around setuptools entry points which enable packages external to Qiskit to advertise they include a synthesis plugin. For details on writing a new plugin refer to the
qiskit.transpiler.passes.synthesis.plugin
module documentation.
-
Added a new transpiler pass,
VF2Layout
. This pass models the layout allocation problem as a subgraph isomorphism problem and uses the VF2 algorithm implementation in retworkx to find a perfect layout (a layout which would not require additional routing) if one exists. The functionality exposed by this new pass is very similar to exisitingCSPLayout
butVF2Layout
is significantly faster.
Known Issues¶
-
The
"ket"
convention in the"latex"
drawer ofStatevector.draw()
is only valid for states comprising purely of qubits. If you are using states with some spaces of dimension greater than two, you should either passconvention="vector"
, or use a different drawer.
-
The OpenQASM 3 export capabilities are in a beta state, and some features of Qiskit Terra's
QuantumCircuit
are not yet supported. In particular, you may see errors if you try to export custom subroutines with classical parameters, and there is no provision yet for exporting pulse-calibrated operations into OpenPulse.
-
When running the
BasisTranslator
in isolation with thetarget
argument set to aTarget
object, where some single-qubit gates can only apply to non-overlapping sets of qubits, the output circuit might incorrectly include operations on a qubit that are not allowed by theTarget
. For example, if you ran:from qiskit.circuit import QuantumCircuit , Parameter from qiskit.circuit.library import UGate , RZGate , XGate , SXGate , CXGate from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel from qiskit.transpiler import PassManager , Target , InstructionProperties from qiskit.transpiler.passes import BasisTranslator gmap = Target () # U gate in qubit 0. theta = Parameter ( 'theta' ) phi = Parameter ( 'phi' ) lam = Parameter ( 'lambda' ) u_props = { ( 0 ,): InstructionProperties ( duration = 5.23e-8 , error = 0.00038115 ), } gmap . add_instruction ( UGate ( theta , phi , lam ), u_props ) # Rz gate in qubit 1. phi = Parameter ( "phi" ) rz_props = { ( 1 ,): InstructionProperties ( duration = 0.0 , error = 0 ), } gmap . add_instruction ( RZGate ( phi ), rz_props ) # X gate in qubit 1. x_props = { ( 1 ,): InstructionProperties ( duration = 3.5555555555555554e-08 , error = 0.00020056469709026198 ), } gmap . add_instruction ( XGate (), x_props ) # SX gate in qubit 1. sx_props = { ( 1 ,): InstructionProperties ( duration = 3.5555555555555554e-08 , error = 0.00020056469709026198 ), } gmap . add_instruction ( SXGate (), sx_props ) cx_props = { ( 0 , 1 ): InstructionProperties ( duration = 5.23e-7 , error = 0.00098115 ), ( 1 , 0 ): InstructionProperties ( duration = 4.52e-7 , error = 0.00132115 ), } gmap . add_instruction ( CXGate (), cx_props ) bt_pass = BasisTranslator ( sel , target_basis = None , target = gmap ) qc = QuantumCircuit ( 2 ) qc . iswap ( 0 , 1 ) output = bt_pass ( qc )
output
will haveRZGate
andSXGate
on qubit 0, even though this is forbidden. To correct this you can normally run the basis translator a second time (i.e.output = bt_pass(output)
in the above example) to correct this. This should not affect the output of running thetranspile()
function and is only an issue if you run the pass by itself.
Upgrade Notes¶
-
Starting with this version,
from qiskit import *
will not import submodules, but only a selected list of objects. This might break existing code usingfrom qiskit import *
and referring to objects that are not part of the current namespace. As a reminder,import *
is considered bad practice and it should not be used in production code. Qiskit sets__all__
inqiskit/__init__.py
as a way to mitigate the effects of said bad practice. If your code raisesname '<something>' is not defined
, addfrom qiskit import <something>
and try again.
-
The preset pass managers for optimization levels 0, 1, 2, and 3 which are generated by
level_0_pass_manager()
,level_1_pass_manager()
,level_2_pass_manager()
, andlevel_3_pass_manager()
respectively will no longer unconditionally run theTimeUnitConversion
. Previously, the preset pass managers would always run this pass regardless of the inputs to the transpiler and the circuit. Now this pass will only be run if ascheduling_method
parameter is set or the circuit contains aDelay
instruction and theinstruction_durations
parameter is set. This change was made in the interest of runtime performance as in some cases runningtranspile()
on circuits with a large number of gates and no delays, timing, or scheduling being used theTimeUnitConversion
could be the largest bottleneck in the transpilation.
-
The default method for
BIPMapping
is nowbalanced
rather thandepth
. This new objective generally achieves a better result, as it factors in both the circuit depth and the gate error.
-
The
sort_parameters_by_name
of theVQE
class has been removed, following its deprecation in Qiskit Terra 0.18. There is no alternative provided, as the new ordering of parameters is the more natural sort order.
-
The circuit drawers
QuantumCircuit.draw()
andcircuit_drawer()
with thelatex
option will now save their images in a format determined the file extension (if a file name is provided). Previously, they would always save in PNG format. They now raiseValueError
if the image format is not known. This was done to make it easier to save the image in different formats.
-
The core dependency
retworkx
had its version requirement bumped to 0.10.1, up from 0.9. This enables several performance improvements across different transpilation passes.
-
The previously deprecated
condition
kwarg, which was deprecated as part of the 0.15.0 release, has been removed fromDAGCircuit.apply_operation_back()
andDAGCircuit.apply_operation_front()
. Instead set thecondition
attribute on theInstruction
instances being added to theDAGCircuit
usingInstruction.c_if()
.
-
The
DAGCircuit.extend_back()
method has been removed. It was originally deprecated in the 0.13.0 release. Instead you can use theDAGCircuit.compose()
method which is more general and provides the same functionality.
-
The
DAGCircuit.compose_back()
method has been removed. It was originally deprecated in the 0.13.0 release. Instead you can use theDAGCircuit.compose()
method which is more general and provides the same functionality.
-
The
edge_map
kwarg of theDAGCircuit
methodcompose()
has been removed. It was originally deprecated in the 0.14.0 release. The method takes aqubits
andclbits
kwargs to specify the positional order of bits to compose onto instead of using a dictionary mapping thatedge_map
previously provided.
-
The
DAGCircuit.twoQ_gates()
method has been removed. It was originally deprecated in the 0.13.0 release. Instead,DAGCircuit.two_qubit_ops()
should be used.
-
The
DAGCircuit.threeQ_or_more_gates()
method has been removed. It was originally deprecated in the 0.13.0 release. Instead,DAGCircuit.multi_qubit_ops()
method should be used.
-
Named access for the first positional argument for the constructor of the
SingleQubitUnitary
class withu
has been removed. It was originally deprecated in the 0.14.0 release. Instead, the first positional argument can be set using the nameunitary_matrix
(or just set it positionally instead of by name).
-
Named access for the first positional argument for the
QuantumCircuit
methodsqu
withu
has been removed. It was originally deprecated in the 0.14.0 release. Instead the first positional argument can be set using the nameunitary_matrix
(or just set it positionally instead of by name).
-
The unused
proc
andnested_scope
kwargs for theqasm()
method of the QASM node classes in theqiskit.qasm.node
module have been removed. They were originally deprecated in the 0.15.0 release.
-
The unused
proc
andnested_scope
kwargs for thelatex()
method of the QASM node classes in theqiskit.qasm.node
module have been removed. They were originally deprecated in the 0.15.0 release.
-
The unused
proc
andnested_scope
kwargs for thereal()
method of the QASM node classes in theqiskit.qasm.node
module have been removed. They were originally deprecated in the 0.15.0 release.
-
The output of
Statevector.draw()
when using"latex"
output is now the new"ket"
convention if plotting a state comprised purely of qubits. This was changed to make reading the output clearer, especially in educational contexts, because it shows the ket labels, and only displays the nonzero elements.
-
When running
execute()
with aBackendV1
backend the default values for the kwargsshots
,max_credits
,meas_level
,meas_return
andmemory_slot_size
will now be whatever the set default is on the target backend'soptions
attribute. Previously these defaults were set to match the default values when callingexecute()
with a legacyBaseBackend
backend. For example:from qiskit.test.mock import FakeMumbai from qiskit import QuantumCircuit , execute circuit = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc . measure_all () backend = FakeMumbai () backend . set_options ( shots = 4096 ) execute ( qc , backend )
will now run with
4096
shots. While in previous releases it would run with1024
.
-
The minimum supported version of Matplotlib has been raised from 2.1.0 to 3.3.0. You will now need to have Matplotlib 3.3.0 installed if you're using Matplotlib-based visualization functions such as the
'mpl'
backend for thecircuit_drawer()
function or theplot_bloch_vector()
function. This was done for two reasons, the first is because recent versions of Matplotlib have deprecated the use of APIs around 3D visualizations that were compatible with older releases and second installing older versions of Matplotlib was becoming increasingly difficult as matplotlib's upstream dependencies have caused incompatiblities that made testing moving forward more difficult.
-
The internal use of the random number generator in
random_circuit()
was adjusted, which will change the output from previous versions, even with a fixed seed. This was done to greatly improve the runtime scaling with the number of qubits being used. If you were depending on an identical output from a previous version it is recommended that you useqpy_serialization.dump()
to save the random circuit generated with a previous version and instead of re-generating it with the new release, and instead just useqpy_serialization.load()
to load that saved circuit.
-
The use of
*
(__mul__
) for thedot()
method and@
(__matmul__
) for thecompose()
method ofBaseOperator
(which is the parent of all the operator classes inqiskit.quantum_info
including classes likeOperator
andPauli
) is no longer supported. The use of these operators were previously deprecated in 0.17.0 release. Instead you should use thedot()
andcompose()
methods directly, or the&
operator (__and__
) can be used forcompose()
. For example, if you were previously using the operator like:from qiskit.quantum_info import random_hermitian op_a = random_hermitian ( 4 ) op_b = random_hermitian ( 4 ) new_op = op_a @ op_b
this should be changed to be:
from qiskit.quantum_info import random_hermitian op_a = random_hermitian ( 4 ) op_b = random_hermitian ( 4 ) new_op = op_a . compose ( op_b )
or:
-
Various methods of assigning parameters to operands of pulse program instructions have been removed, having been deprecated in Qiskit Terra 0.17. These include:
-
the
assign()
method ofpulse.Instruction
. -
the
assign()
method ofChannel
, which is the base ofAcquireChannel
,SnapshotChannel
,MemorySlot
andRegisterSlot
. -
the
assign()
andassign_parameters()
methods ofParametricPulse
, which is the base ofpulse.Gaussian
,pulse.GaussianSquare
,pulse.Drag
andpulse.Constant
.
These parameters should be assigned from the pulse program (
pulse.Schedule
andpulse.ScheduleBlock
) rather than operands of the pulse program instruction. -
-
The
flatten()
method ofpulse.Instruction
andqiskit.pulse.Schedule
has been removed and no longer exists as per the deprecation notice from Qiskit Terra 0.17. This transformation is defined as a standalone function inqiskit.pulse.transforms.canonicalization.flatten()
.
-
qiskit.pulse.interfaces.ScheduleComponent
has been removed and no longer exists as per the deprecation notice from Qiskit Terra 0.15. No alternative class will be provided.
-
Legacy pulse drawer arguments have been removed from
pulse.Waveform.draw()
,Schedule.draw()
andScheduleBlock.draw()
and no longer exist as per the deprecation notice from Qiskit Terra 0.16. Now these draw methods support only V2 pulse drawer arguments. See method documentations for details.
-
The
qiskit.pulse.reschedule
module has been removed and this import path no longer exist as per the deprecation notice from Qiskit Terra 0.14. Useqiskit.pulse.transforms
instead.
-
A protected method
Schedule._children()
has been removed and replaced by a protected instance variable as per the deprecation notice from Qiskit Terra 0.17. This is now provided as a public attributeSchedule.children
.
-
Timeslot relevant methods and properties have been removed and no longer exist in
ScheduleBlock
as per the deprecation notice from Qiskit Terra 0.17. Since this representation doesn't have notion of instruction timet0
, the timeslot information will be available after it is transformed to aSchedule
. Corresponding attributes have been provided after this conversion, but they are no longer supported. The following attributes are removed:-
timeslots
-
start_time
-
stop_time
-
ch_start_time
-
ch_stop_time
-
shift
-
insert
-
-
Alignment pulse schedule transforms have been removed and no longer exist as per the deprecation notice from Qiskit Terra 0.17. These transforms are integrated and implemented in the
AlignmentKind
context of the schedule block. The following explicit transform functions are removed:-
qiskit.pulse.transforms.align_equispaced
-
qiskit.pulse.transforms.align_func
-
qiskit.pulse.transforms.align_left
-
qiskit.pulse.transforms.align_right
-
qiskit.pulse.transforms.align_sequential
-
-
Redundant pulse builder commands have been removed and no longer exist as per the deprecation notice from Qiskit Terra 0.17.
pulse.builder.call_schedule
andpulse.builder.call_circuit
have been integrated intopulse.builder.call()
.
-
An internal filter override that caused all Qiskit deprecation warnings to be displayed has been removed. This means that the behaviour will now revert to the standard Python behaviour for deprecations; you should only see a
DeprecationWarning
if it was triggered by code in the main script file, interpreter session or Jupyter notebook. The user will no longer be blamed with a warning if internal Qiskit functions call deprecated behaviour. If you write libraries, you should occasionally run with the default warning filters disabled, or have tests which always run with them disabled. See the Python documentation on warnings, and in particular the section on testing for deprecations for more information on how to do this.
-
Certain warnings used to be only issued once, even if triggered from multiple places. This behaviour has been removed, so it is possible that if you call deprecated functions, you may see more warnings than you did before. You should change any deprecated function calls to the suggested versions, because the deprecated forms will be removed in future Qiskit releases.
-
The deprecated
qiskit.schemas
module and theqiskit.validation
module which build jsonschema validator from the schemas have been removed. This was deprecated in the 0.17.0 release and has been replaced with a dedicated repository for the IBM Quantum API payload schemas.If you were relying on the schema files previously packaged in
qiskit.schemas
or the validators built on them you should use that repository and create validators from the schema files it contains.
-
The functions
qiskit.qobj.validate_qobj_against_schema
andqiskit.qobj.common.validator
along with thevalidate
kwarg of the methodsQasmQobj.to_dict()
,PulseQobj.to_dict()
, andQobj.to_dict()
have been removed. These were deprecated in the 0.17.0 release. If you were using these function you will have to manually build jsonschema validation functions forQobj
objects using the jsonschema files from the dedicated repository for the IBM Quantum API payload schemas.
-
The
fastjsonschema
andjsonschema
packages are no longer in the requirements list for qiskit-terra. The internal use of jsonschema has been removed and they are no longer required to use qiskit-terra.
-
The exception raised by the
assemble()
function when invalid parameters are passed in for constructing aPulseQobj
have changed from aSchemaValidationError
to aQiskitError
. This was necessary because theSchemaValidationError
class was removed along with the rest of the deprecatedqiskit.schemas
andqiskit.validation
. This also makes it more consistent with other error conditions fromassemble()
which were already raising aQiskitError
.
-
The default routing pass and layout pass for transpiler optimization level 3 has changed to use
SabreSwap
andSabreLayout
respectively. This was done to improve the quality of the output result, as using the sabre passes produces better results than usingStochasticSwap
andDenseLayout
, which were used as the defaults in prior releases. This change will improve the quality of the results when runningtranspile()
orexecute()
functions with theoptimization_level
kwarg set to3
. While this is generally an improvement, if you need to retain the previous behavior for any reason you can do this by explicitly setting therouting_method="stochastic"
andlayout_method="dense"
when callingtranspile()
withoptimization_level=3
.
-
The return type of
pauli_basis()
will change fromPauliTable
toPauliList
in a future release of Qiskit Terra. To immediately swap to the new behaviour, pass the keyword argumentpauli_list=True
.
-
The
name
attribute of theSingleQubitUnitary
gate class has been changed fromunitary
tosqu
. This was necessary to avoid a conflict with theUnitaryGate
class's name which was alsounitary
since the 2 gates are not the same and don't have the same implementation (and can't be used interchangeably).
-
The minimum version of Symengine required for installing has been increased to 0.8.0. This was necessary to fix some issues with the handling of
numpy.float16
andnumpy.float32
values when runningbind()
to bind parameters in aParameterExpression
.
-
A new dependency stevedore has been added to the requirements list. This is required by qiskit-terra as it is used to build the unitary synthesis plugin interface.
Deprecation Notes¶
-
The
gate
attribute and initialization parameter ofqiskit.transpiler.passes.Decompose
is deprecated, and will be removed in a future release. Instead of this single gate, you should pass a list of gate names to the new parametergates_to_decompose
. This was done as the new form allows you to select more than one gate as a decomposition target, which is more flexible, and does not need to re-run the pass several times to decompose a set of gates.
-
There has been a significant transpiler pass reorganization regarding calibrations. The import paths:
from qiskit.transpiler.passes.scheduling.calibration_creators import RZXCalibrationBuilder from qiskit.transpiler.passes.scheduling.calibration_creators import RZXCalibrationBuilderNoEcho
are deprecated, and will be removed in a future release. The import path:
from qiskit.transpiler.passes.scheduling.rzx_templates import rzx_templates
is also deprecated, and will be removed in a future release. You should use the new import paths:
from qiskit.transpiler.passes import RZXCalibrationBuilder from qiskit.transpiler.passes import RZXCalibrationBuilderNoEcho from qiskit.transpiler.passes.calibration.rzx_templates import rzx_templates
-
The
DAGNode
class is being deprecated as a standalone class and will be used in the future only as the parent class forDAGOpNode
,DAGInNode
, andDAGOutNode
. As part of this deprecation, the following kwargs and associated attributes inDAGNode
are also being deprecated:type
,op
, andwire
.
-
For the constructor of the
RZXCalibrationBuilder
passing a backend either as the first positional argument or with the namedbackend
kwarg is deprecated and will no longer work in a future release. Instead aInstructionScheduleMap
should be passed directly to theinstruction_schedule_map
kwarg and a list of channel name lists for each qubit should be passed directly toqubit_channel_mapping
. For example, if you were calling the pass like:from qiskit.transpiler.passes import RZXCalibrationBuilder from qiskit.test.mock import FakeMumbai backend = FakeMumbai () cal_pass = RZXCalibrationBuilder ( backend )
instead you should call it like:
from qiskit.transpiler.passes import RZXCalibrationBuilder from qiskit.test.mock import FakeMumbai backend = FakeMumbai () inst_map = backend . defaults () . instruction_schedule_map channel_map = self . backend . configuration () . qubit_channel_mapping cal_pass = RZXCalibrationBuilder ( instruction_schedule_map = inst_map , qubit_channel_mapping = channel_map , )
This change is necessary because as a general rule backend objects are not pickle serializable and it would break when it was used with multiple processes inside of
transpile()
when compiling multiple circuits at once.
-
The
label
property of classMCMT
and subclassMCMTVChain
has been deprecated and will be removed in a future release. Consequently, thelabel
kwarg on the constructor for both classes is also deprecated, along with thelabel
kwarg of methodMCMT.control()
. Currently, thelabel
property is used to name the controlled target when it is comprised of more than one target qubit, however, this was never intended to be user-specifiable, and can result in an incorrect MCMT gate if the name of a well-known operation is used. After deprecation, thelabel
property will no longer be user-specifiable. However, you can get the generated name of the controlled target viaMCMT . data [ 0 ][ 0 ] . base_gate . name
-
The
subgraph()
method of theCouplingMap
class is deprecated and will be removed in a future release. Instead thereduce()
method should be used, which does the same thing except it preserves the node list order for the outputCouplingMap
(whilesubgraph()
did not preserve list order).
-
Creating an instance of
InstructionSet
with thecircuit_cregs
keyword argument is deprecated. In general, these classes never need to be constructed by users (but are used internally), but should you need to, you should pass a callable as theresource_requester
keyword argument. For example:from qiskit.circuit import Clbit , ClassicalRegister , InstructionSet from qiskit.circuit.exceptions import CircuitError def my_requester ( bits , registers ): bits_set = set ( bits ) bits_flat = tuple ( bits ) registers_set = set ( registers ) def requester ( specifier ): if isinstance ( specifer , Clbit ) and specifier in bits_set : return specifier if isinstance ( specifer , ClassicalRegster ) and specifier in register_set : return specifier if isinstance ( specifier , int ) and 0 <= specifier < len ( bits_flat ): return bits_flat [ specifier ] raise CircuitError ( f "Unknown resource: { specifier } " ) return requester my_bits = [ Clbit () for _ in [ None ] * 5 ] my_registers = [ ClassicalRegister ( n ) for n in range ( 3 )] InstructionSet ( resource_requester = my_requester ( my_bits , my_registers ))
-
The use of the measurement mitigation classes
qiskit.ignis.mitigation.CompleteMeasFitter
andqiskit.ignis.mitigation.TensoredMeasFitter
fromqiskit-ignis
as values for themeasurement_error_mitigation_cls
kwarg of the constructor for theQuantumInstance
class is deprecated and will be removed in a future release. Instead the equivalent classes fromqiskit.utils.mitigation
,CompleteMeasFitter
andTensoredMeasFitter
should be used. This was necessary as theqiskit-ignis
project is now deprecated and will no longer be supported in the near future. It's worth noting that unlike the equivalent classes fromqiskit-ignis
the versions fromqiskit.utils.mitigation
are supported only in their use withQuantumInstance
(i.e. as a class not an instance with themeasurement_error_mitigation_cls
kwarg) and not intended for standalone use.
-
The
Optimizer.optimize()
method for all the optimizers (Optimizer
and derived classes) is now deprecated and will be removed in a future release. Instead, theOptimizer.minimize()
method should be used which mimics the signature of SciPy'sminimize()
function.To replace the current optimize call with minimize you can replace
xopt , fopt , nfev = optimizer . optimize ( num_vars , objective_function , gradient_function , variable_bounds , initial_point , )
with
result = optimizer . minimize ( fun = objective_function , x0 = initial_point , jac = gradient_function , bounds = variable_bounds , ) xopt , fopt , nfev = result . x , result . fun , result . nfev
-
Importing the
qiskit.util
module will now issue aDeprecationWarning
. Users should instead import all the same functionality fromqiskit.utils
. Theutil
module has been deprecated since Terra 0.17, but previously did not issue a warning. It will be removed in Terra 0.20.
-
The property
table
is deprecated, and will be removed in a future release. This is becauseSparsePauliOp
has been updated to internally usePauliList
instead ofPauliTable
. This is in order to significantly improve performance. You should now access thePauliList
data by using theSparsePauliOp.paulis
attribute.
Bug Fixes¶
-
Fixed a bug where many layout methods would ignore 3-or-more qubit gates, resulting in unexpected layout-allocation decisions. The transpiler pass
Unroll3qOrMore
is now being executed before the layout pass in all the preset pass managers whentranspile()
is called. Fixed #7156.
-
Disassembled circuits now inherit calibrations from assembled
QasmQobj
and experiments. Fixes #5348.
-
Fixed setting the
ansatz
oroptimizer
attributes of aVQE
instance toNone
resulting in a buggy behavior. See #7093 for details.
-
Fixed addition of
PauliList
s withqargs
. The method used to raise a runtime error if the operands had different numbers of qubits.
-
Fixed an issue causing an error when trying to compute a gradient with the
CircuitGradient
class for a gate that was not a supported gate. This bugfix transpiles a given gate to the set of supported gates for a requested gradient method. Fixes #6918.
-
Removed calibration results when using error mitigation with the
execute()
method ofQuantumInstance
. Fixes #7129.
-
Fixed a deprecation warning emitted when running
QuantumCircuit.draw()
orcircuit_drawer()
with Sympy 1.9 installed, mentioning the Sympy functionexpr_free_symbols()
. The circuit drawers previously made use of this method when finding instances of symbolic constants.
-
Fixed an issue where the
ax
kwarg and thefigwidth
option in thestyle
kwarg for thempl
circuit drawer did not scale properly. Users can now pass anax
from a Matplotlib subplot to thempl
circuit drawer and the circuit will be drawn within the boundaries of that subplot. Alternatively, users can set thefigwidth
in inches in thestyle
dict kwarg and the drawing will scale to the width in inches that was set. Fixed #6367.
-
Fixed an issue with the
circuit_drawer()
function anddraw()
method ofQuantumCircuit
. When displaying ameasure
instruction targeted on a classical bit instead of a register, using thelatex
drawer option, the drawer would fail.
-
Fixed an issue with the
circuit_drawer()
function anddraw()
method ofQuantumCircuit
. With any of the 3 drawer options,mpl
,latex
, ortext
, if a gate with a classical condition was encountered that was conditioned on a classical bit without a register, the drawer would fail.
-
Fixed an issue with the
circuit_drawer()
function anddraw()
method ofQuantumCircuit
. With any of the 3 drawer options,mpl
,latex
, ortext
, if a gate with a classical condition was conditioned on the same classical bit as ameasure
and the bit that the measure targeted did not have a register, the drawer would fail.
-
C3SXGate
now has a correct decomposition and matrix representation. Previously it was equivalent toSdgXGate().control(3)
, rather than the intendedSXGate().control(3)
.
-
The member
name
ofqiskit.test.mock.utils.ConfigurableFakeBackend
has been changed tobackend_name
. This was done to avoid a conflict with thename()
method inherited from the parent abstractBackendV1
class. This makesConfigurableFakeBackend
compatible with anything expecting aBackendV1
object. However, if you were using thename
attribute directly before you will now need to either call it as a method or access thebackend_name
attribute instead.
-
Fixed an issue where calling
QuantumCircuit.decompose()
on a circuit containing anInstruction
whosedefinition
attribute was empty would leave the instruction in place, instead of decomposing it into zero operations. For example, with a circuit:from qiskit.circuit import QuantumCircuit empty = QuantumCircuit ( 1 , name = "decompose me!" ) circuit = QuantumCircuit ( 1 ) circuit . append ( empty . to_gate (), [ 0 ])
Previously, calling
circuit.decompose()
would not change the circuit. Now, the decomposition will correct decomposeempty
into zero instructions. See #6997 for more.
-
Fixed an issue with the
circuit_drawer()
function anddraw()
method ofQuantumCircuit
. When displaying ameasure
instruction containing a classicalcondition
using thempl
orlatex
options, thecondition
information would sometimes overwrite themeasure
display.
-
Fixed an issue with the
circuit_drawer()
function anddraw()
method ofQuantumCircuit
. Thempl
drawer used hex notation to display thecondition
value, whereas thetext
andlatex
drawers used decimal notation. Now all three drawers use hex notation.
-
Fixed a bug in the Hoare optimizer transpilation pass where it could attempt to remove a gate twice if it could be separately combined with both its predecessor and its successor to form the identity. Refer to #7271 for more details.
-
Making an instruction conditional with the standard
InstructionSet.c_if()
method with integer indices is now consistent with the numbering scheme used by theQuantumCircuit
the instructions are part of. Previously, if there were twoClassicalRegister
s with overlappingClbit
s, the numbering would be incorrect. See #7246 for more detail.
-
Making an instruction conditional with the standard
InstructionSet.c_if()
method will now succeed, even if there are noClassicalRegister
s in the circuit. See #7250 for more detail.
-
Making an instruction conditional with the standard
InstructionSet.c_if()
method when using aClbit
that is contained in aClassicalRegister
of size one will now correctly create a condition on the bit, not the register. See #7255 for more detail.
-
Trying to make an instruction conditional with the standard
InstructionSet.c_if()
method will now correctly raise an error if the classical resource is not present in the circuit. See #7255 for more detail.
-
Fixed a compatibility issue with Matplotlib 3.5, where the Bloch sphere would fail to render if it had any vectors attached, such as by using
plot_bloch_vector
. See #7272 for more detail.
-
Fixed an issue with the
NLocal.add_layer()
method incorrectly appending layers if theNLocal
object had already been built.
-
Fixed an issue with pickling
InstructionScheduleMap
object when using Python 3.6. See #6944 for details.
-
Complex valued pulse parameter assignment with symengine has been fixed. For example,
from qiskit import circuit , pulse import numpy as np amp = circuit . Parameter ( "amp" ) phase = circuit . Parameter ( "phase" ) with pulse . build () as sched : pulse . play ( pulse . Gaussian ( 160 , amp * np . exp ( 1 j * phase ), 40 ), pulse . DriveChannel ( 0 )) sched . assign_parameters ({ amp : 0.1 , phase : 1.57 }, inplace = True )
The assigned amplitude has been shown as
ParameterExpression(0.1*exp(1.57*I))
after the use ofsymengine
was introduced in the 0.18.0 release. This is now correctly evaluated and shown as7.96327e-05 + 0.0999999683j
.
-
Fixed an issue where
QAOA.construct_circuit()
with different operators with same number of qubits would generate the same circuit each time. See #7223 for more detail.
-
Fixed an issue where
QAOAAnsatz
had an incorrect number of parameters if identities ofPauliSumOp
were given, e.g.,PauliSumOp.from_list([("III", 1)])
. See #7225 for more detail.
-
Fixed a bug where the
QuantumCircuit.qasm()
method could return OpenQASM 2 instructions with invalid identifiers. The same bug was fixed forUnitaryGate
.
-
Fixed an issue where trying to display registerless bits would cause a failure of the
mpl
and thelatex
circuit drawers. A leading_
has been removed from the display of registerless bits' numbers in thetext
drawer. Fixed #6732.
-
For one-bit registers, all of the circuit drawers now display only the register name and no longer show the
0
subscript. Fixed #5784.
-
Fixed naming collisions of implicit registers in
QuantumCircuit.qasm
when dealing with registerless qubits and clbits. Previously, registerless qubits and clbits were put into correspondingqreg
andcreg
both calledregless
, despite the collision. They will now have separate, deterministically generated names, which will not clash with any user-defined register names in the circuit.
-
Fixed an issue in scheduling of circuits with clbits operations, e.g. measurements, conditional gates, updating
ASAPSchedule
,ALAPSchedule
, andAlignMeasures
. The updated schedulers assume all clbits I/O operations take no time,measure
writes the measured value to a clbit at the end, andc_if
reads the conditional value in clbit(s) at the beginning. Fixed #7006.
-
Calling
transpile
on an empty list will now correctly return an empty list without issuing a warning. Fixed #7287.
-
Fixed an issue in
PiecewiseChebyshev
when the function to be approximated was constant. In these cases, you should now pass the constant directly as thef_x
argument, rather than using a function, such as:from qiskit.circuit.library.arithmetic import PiecewiseChebyshev PiecewiseChebyshev ( 1.0 , degree = 3 )
See #6707 for more details.
-
If an
HHL
algorithm instance was constructed without aQuantumInstance
(the default), attempts to use the getter and setter properties to read or set an instance later would fail. The getters and setters now work as expected.
-
The
QuantumCircuit.qasm()
method now edits the names of copies of the instructions present in the circuit, not the original instructions that live incircuit.data
. Refer to #6952 for more details.
-
Fixed a bug in
PauliSumOp.permute()
causing the error:QiskitError : 'Pauli string label "" is not valid.'
if the permutation had the same number of Pauli terms. Calling
permute([2, 1, 0])
onX ^ Y ^ Z
no longer raises an error, and now returnsZ ^ Y ^ X
.
-
Fixed a bug where the parameter bounds for the mixer parameters in the
QAOAAnsatz
were not been set.
-
Fixed determination of final operations (barriers and measures) in pass
RemoveFinalMeasurements
and in methodremove_final_measurements()
of classQuantumCircuit
which previously considered only nodes immediately preceding an output node.
-
Fixed determination of final operations in pass
RemoveFinalMeasurements
and in methodremove_final_measurements()
of classQuantumCircuit
which could wrongly consider a barrier to be final, even if other circuit operations followed it.
-
Fixed multi-bit classical register removal in pass
RemoveFinalMeasurements
and in methodremove_final_measurements()
of classQuantumCircuit
where classical registers were not removed even if other bits were idle, unless a final measure was done into each and every bit. Now, classical registers that become idle as a result of removing final measurements and barriers are always removed. Classical bits are removed if they are referenced only by removed registers or are not referenced at all and became idle due to the removal. This fix also adds proper handling of registers with shared underlying bits.
-
Fixed an issue with
RemoveFinalMeasurements
which could cause the resultingDAGCircuit
to become invalid. See #7196 for more details.
-
Fixed an issue with method
remove_final_measurements()
of classQuantumCircuit
that causedQuantumCircuit.clbits
to be incorrect after invocation. Refer to #7089 for details.
-
When tapering an empty zero operator in
qiskit.opflow
, the code, on detecting it was zero, logged a warning and returned the original operator. Such operators are commonly found in the auxiliary operators, when using Qiskit Nature, and the above behavior causedVQE
to throw an exception as tapered non-zero operators were a different number of qubits from the tapered zero operators (since taper has returned the input operator unchanged). The code will now correctly taper a zero operator such that the number of qubits is reduced as expected and matches to tapered non-zero operators e.g`0*"IIII"`
when we are tapering by 3 qubits will become0*"I"
.
-
Fixed an issue with the
draw()
method andcircuit_drawer()
function, where a custom style set via the user config file (i.e.settings.conf
) would ignore the set value of thecircuit_mpl_style
field if thestyle
kwarg on the function/method was not set.
Other Notes¶
-
The string cast for
qiskit.circuit.ParameterExpression
does not have full precision anymore. This removes the trailing 0s when printing parameters that are bound to floats. This has consequences for QASM serialization and the circuit text drawer:>>> from qiskit.circuit import Parameter >>> x = Parameter ( 'x' ) >>> str ( x . bind ({ x : 0.5 })) '0.5' # instead of '0.500000000000000'
-
The
QAOAAnsatz
has been updated to use the parameter symbolγ
for the cost operator andβ
for the mixer operator, as is the standard notation in QAOA literature.
Ignis 0.7.0¶
Prelude¶
This release deprecates the Qiskit Ignis project, it has been supersceded by the Qiskit Experiments project and active development has ceased. While deprecated, critical bug fixes and compatibility fixes will continue to be made to provide users a sufficient opportunity to migrate off of Ignis. After the deprecation period (which will be no shorter than 3 months from this release) the project will be retired and archived.
New Features¶
-
Updated the accreditation protocol to use fitting routine from https://arxiv.org/abs/2103.06603.
AccreditationFitter
now has methods FullAccreditation (previous protocol) and MeanAccreditation (new protocol). In addtition data entry has been changed to either use the result object AppendResult or a list of strings AppendStrings.qiskit.ignis.verification.QOTPCorrectString()
was also added.
-
Added the option for the fast analytical generation of syndrome graphs. The
RepetitionCode
now has a new bool argumentbrute
, which allows to still use the brute force method. Helper classRepetitionCodeSyndromeGenerator
added to facilitate this.
-
The
RepetitionCode
now has keyword argumentsresets
anddelay
. The former determines whether reset gates are inserted after measurement. The latter allows a time (in dt) to be specificed for a delay after each measurement (and reset, if applicable).The
syndrome_measurement()
method ofRepetitionCode
now has keyword argumentsfinal
anddelay
. The former determines whether to add reset gates according to the globalresets
, or to overwrite it with appropriate behavior for the final round of syndrome measurements. The latter allows a time (in dt) to be specificed for a delay after each measurement (and reset, if applicable).
-
The
RepetitionCode
class now supports encoding with x basis states. This can be used by setting thexbasis
keyword argument when constructing aRepetitionCode
object.
Upgrade Notes¶
-
The keyword argument
reset
has been removed from the thesyndrome_measurement()
method ofRepetitionCode
. This is replaced by the globalresets
keyword argument for the class as well as the keyword argumentfinal
forsyndrome_measurement
. In cases where one would previously add the final measurement round usingreset=False
to avoid the final reset gates, one should now usefinal=True
.
-
Remove
ParametrizedSchedule
fromupdate_u_gates()
.ParametrizedSchedule
was deprecated as a part of Qiskit-terra 0.17.0 and will be removed in next release. The function now updates u gates withSchedule
programs involving unassignedParameter
objects.
Deprecation Notes¶
-
Deprecating methods in
AccreditationFitter
namely bound_variation_distance and single_protocol_run
-
The Qiskit Ignis project as a whole has been deprecated and the project will be retired and archived in the future. While deprecated only compatibility fixes and fixes for critical bugs will be made to the proejct. Instead of using Qiskit Ignis you should migrate to use Qiskit Experiments instead. You can refer to the migration guide:
https://github.com/Qiskit/qiskit-ignis#migration-guide
Qiskit 0.32.1¶
IBM Q Provider 0.18.1¶
Bug Fixes¶
-
Fixes #209 where the websocket connection kept timing out when streaming results for a runtime job, due to inactivity, when the job is in a pending state for a long time.
Qiskit 0.32.0¶
IBM Q Provider 0.18.0¶
Upgrade Notes¶
-
Runtime programs will no longer have a
version
field. -
By default,
qiskit.providers.ibmq.runtime.IBMRuntimeService.pprint_programs()
now only prints the summary of each runtime program instead of all of the details. There is a new parameterdetailed
that can be set toTrue
to print all details. -
limit
andskip
parameters have been added toqiskit.providers.ibmq.runtime.IBMRuntimeService.programs()
andqiskit.providers.ibmq.runtime.IBMRuntimeService.pprint_programs()
.limit
can be used to set the number of runtime programs returned andskip
is the number of programs to skip when retrieving programs. -
The data parameter to
qiskit.providers.ibmq.runtime.IBMRuntimeService.upload_program()
can now only be of type string. It can be either the program data, or path to the file that contains program data. -
qiskit.providers.ibmq.runtime.IBMRuntimeService.upload_program()
now takes only two parameters,data
, which is the program passed as a string or the path to the program file and themetadata
, which is passed as a dictionary or path to the metadata JSON file. Inmetadata
thebackend_requirements
,parameters
,return_values
andinterim_results
are now grouped under a specificationsspec
section.parameters
,return_values
andinterim_results
should now be specified as JSON Schema. -
qiskit.providers.ibmq.AccountProvider.run_circuits()
method now takes a backend_name parameter, which is a string, instead of backend, which is aBackend
object. -
The default number of
shots
(represents the number of repetitions of each circuit, for sampling) inqiskit.providers.ibmq.IBMQBackend.run()
, has been increased from 1024 to 4000.
Bug Fixes¶
-
Fixes the issue wherein a runtime job result cannot be retrieved multiple times if the result contains a numpy array.
Qiskit 0.31.0¶
Aer 0.9.1¶
Upgrade Notes¶
-
optimize_ideal_threshold
andoptimize_noisy_threshold
have been removed from the lists of simulator defaults and the documentation. These have had no effect since Aer 0.5.1, but these references to them had remained accidentally.
Bug Fixes¶
-
Fixes #1351 where running an empty
QuantumCircuit
with a noise model set would cause the simulator to crash. -
Fixes #1347 where the behaviour of using the
set_options()
andset_option()
methods of simulator backends could lead to different behavior for some options. -
Fixes an bug where using a Dask Client executor would cause an error at job submission due to the executor Client not being pickleable.
-
Fixed an issue with the matrix_product_state simulation method where the accumulation of small rounding errors during measurement of many quits could sometimes cause a segmentation fault.
-
Fixes an unintended change between qiskit-aer 0.8.0 and 0.9.0 where when running a list of circuits with an invalid circuit using the
automatic
simulation method of theAerSimulator
orQasmSimulator
would raise an exception for an invalid input qobj rather than return partial results for the circuits that were valid. -
Fixes an issue with the standalone simulator where it would return a IBM Quantum API schema invalid response in the case of an error that prevented the simulation from running.
-
Fixes #1346 which was a bug in the handling of the
parameter_binds
kwarg of the backendrun()
method that would result in an error if the parameterized circuit was transpiled to a different set of basis gates than the original parameterizations.
IBM Q Provider 0.17.0¶
Qiskit 0.30.1¶
Terra 0.18.3¶
Prelude¶
This bugfix release fixes a few minor issues in 0.18, including a performance regression in assemble
when dealing with executing QuantumCircuit
objects on pulse-enabled backends.
Bug Fixes¶
-
Fixed #7004 where
AttributeError
was raised when executingScheduleBlock
on a pulse backend. These blocks are now correctly treated as pulse jobs, likeSchedule
. -
Fixed an issue causing an error when binding a complex parameter value to an operator's coefficient. Casts to
float
inPrimitiveOp
were generalized to casts tocomplex
if necessary, but will remainfloat
if there is no imaginary component. Fixes #6976. -
Update the 1-qubit gate errors in
plot_error_map
to use the sx gate instead of the u2 gate, consistent with IBMQ backends.
IBM Q Provider 0.16.0¶
No change
Qiskit 0.30.0¶
Aer 0.9.0¶
Prelude¶
The 0.9 release includes new backend options for parallel exeuction of large numbers of circuits on a HPC cluster using a Dask distributed, along with other general performance improvements and bug fixes.
New Features¶
-
Added support for set_matrix_product_state.
-
Add qiskit library
SXdgGate
andCUGate
to the supported basis gates for the Aer simulator backends. Note that theCUGate
gate is only natively supported for thestatevector
andunitary
methods. For other simulation methods it must be transpiled to the supported basis gates for that method. -
Adds support for N-qubit Pauli gate (
qiskit.circuit.library.generalized_gates.PauliGate
) to all simulation methods of theAerSimulator
andQasmSimulator
. -
Adds the ability to set a custom executor and configure job splitting for executing multiple circuits in parallel on a HPC clustor. A custom executor can be set using the
executor
option, and job splitting is configured by using themax_job_size
option.For example configuring a backend and executing using
backend = AerSimulator ( max_job_size = 1 , executor = custom_executor ) job = backend . run ( circuits )
will split the exection into multiple jobs each containing a single circuit. If job splitting is enabled the
run
method will return aAerJobSet
object containing all the individualAerJob
classes. After all individual jobs finish running the job results are automatically combined into a single Result object that is returned byjob.result()
.Supported executors include those in the Python
concurrent.futures
module (eg.ThreadPoolExecutor
,ProcessPoolExecutor
), and Dask distributed Client executors if the optional dask library is installed. Using a Dask executor allows configuring parallel execution of multiple circuits on HPC clusters. See the Dask executor API Documentation for additional details on using Dask executors for HPC simulation. -
Adds ability to record logging data for the
matrix_product_state
simulation method to the experiment result metadata by setting the backend optionmps_log_data=True
. The saved data includes the bond dimensions and the discarded value (the sum of the squares of the Schmidt coeffients that were discarded by approximation) after every relevant circuit instruction. -
The
run()
method for theAerSimulator
,QasmSimulator
,StatevectorSimulator
, andUnitarySimulator
has a new kwarg,parameter_binds
which is used to provide a list of values to use for any unbound parameters in the inbound circuit. For example:from qiskit.circuit import QuantumCircuit , Parameter from qiskit.providers.aer import AerSimulator shots = 1000 backend = AerSimulator () circuit = QuantumCircuit ( 2 ) theta = Parameter ( 'theta' ) circuit . rx ( theta , 0 ) circuit . cx ( 0 , 1 ) circuit . measure_all () parameter_binds = [{ theta : [ 0 , 3.14 , 6.28 ]}] backend . run ( circuit , shots = shots , parameter_binds = parameter_binds ) . result ()
will run the input circuit 3 times with the values 0, 3.14, and 6.28 for theta. When running with multiple parameters the length of the value lists must all be the same. When running with multiple circuits, the length of
parameter_binds
must match the number of input circuits (you can use an empty dict,{}
, if there are no binds for a circuit). -
The
PulseSimulator
can now takeQuantumCircuit
objects on therun()
. Previously, it only would exceptSchedule
objects as input torun()
. When a circuit or list of circuits is passed to the simulator it will callschedule()
to convert the circuits to a schedule before executing the circuit. For example:from qiskit.circuit import QuantumCircuit from qiskit.compiler import transpile from qiskit.test.mock import FakeVigo from qiskit.providers.aer.backends import PulseSimulator backend = PulseSimulator . from_backend ( FakeVigo ()) circuit = QuantumCircuit ( 2 ) circuit . h ( 0 ) circuit . cx ( 0 , 1 ) circuit . measure_all () transpiled_circuit = transpile ( circuit , backend ) backend . run ( circuit )
Upgrade Notes¶
-
The default basis for the
NoiseModel
class has been changed from["id", "u3", "cx"]
to["id", "rz", "sx", "cx"]
due to the deprecation of theu3
circuit method in qiskit-terra and change of qiskit-ibmq-provider backend basis gates. To use the old basis gates you can initialize a noise model with custom basis gates asNoiseModel(basis_gates=["id", "u3", "cx"])
. -
Removed the
backend_options
kwarg from therun
methnod of Aer backends that was deprecated in qiskit-aer 0.7. All run options must now be passed as separate kwargs. -
Removed passing
system_model
as a positional arg for therun
method of thePulseSimulator
.
Deprecation Notes¶
-
Passing an assembled qobj directly to the
run()
method of the Aer simulator backends has been deprecated in favor of passing transpiled circuits directly asbackend.run(circuits, **run_options)
. -
All snapshot instructions in
qiskit.providers.aer.extensions
have been deprecated. For replacement use the save instructions from theqiskit.providers.aer.library
module. -
Adding non-local quantum errors to a
NoiseModel
has been deprecated due to inconsistencies in how this noise is applied to the optimized circuit. Non-local noise should be manually added to a scheduled circuit in Qiskit using a custom transpiler pass before being run on the simulator. -
Use of the
method
option of theStatevectorSimulator
, andUnitarySimulator
to run a GPU simulation has been deprecated. To run a GPU simulation on a compatible system use the optiondevice='GPU'
instead.
Bug Fixes¶
-
Fixes performance issue with how the
basis_gates
configuration attribute was set. Previously there were unintended side-effects to the backend class which could cause repeated simulation runtime to incrementally increase. Refer to #1229 <https://github.com/Qiskit/qiskit-aer/issues/1229> for more information and examples. -
Fixed bug in MPS::apply_kraus. After applying the kraus matrix to the relevant qubits, we should propagate the changes to the neighboring qubits.
-
Fixes a bug where qiskit-terra assumes that qubits in a multiplexer gate are first the targets and then the controls of the gate while qiskit-aer assumes the opposite order.
-
Fixes a bug introduced in 0.8.0 where GPU simulations would allocate unneeded host memory in addition to the GPU memory.
-
Fixes bug where the initialize instruction would disable measurement sampling optimization for the statevector and matrix product state simulation methods even when it was the first circuit instruction or applied to all qubits and hence deterministic.
-
Fix issue #1196 by using the inner products with the computational basis states to calculate the norm rather than the norm estimation algorithm.
-
Fixes a bug in the
stabilizer
simulator method of theQasmSimulator
andAerSimulator
where the expectation value for thesave_expectation_value
andsnapshot_expectation_value
could have the wrong sign for certainY
Pauli's. -
Fixes bug where the if the required memory is smaller than the system memory the multi-chunk simulation method was enabled and simulation was still started. This case will now throw an insufficient memory exception.
-
Fixes issue where setting the
shots
option for a backend withset_options(shots=k)
was always running the default number of shots (1024) rather than the specified value. -
Fixes a bug in how the
AerSimulator
handled the option value formax_parallel_experiments=1
. Previously this was treated the same asmax_parallel_experiments=0
. -
Fixes bug in the
extended_stabilizer
simulation method where it incorrectly treated qelay gate and multi-qubit Pauli instructions as unsupported. -
Fixes typo in the
AerSimulator
andQasmSimulator
options for theextended_stabilizer_norm_estimation_repetitions
option. -
Fixes bug with applying the
unitary
gate in using thematrix_product_state
simulation method which did not correctly support permutations in the ordering of the qubits on which the gate is applied. -
Fixes an issue where gate fusion could still be enabled for the
matrix_product_state
simulation method even though it is not supported. Now fusion is always disabled for this method. -
Fixed bug in the
matrix_product_state
simulation method in computing the normalization following truncation of the Schmidt coefficients after performing the SVD.
Other Notes¶
-
Improves the performance of the measurement sampling algorithm for the
matrix_product_state
simulation method. The new default behaviour is to always sample using the improvedmps_apply_measure
method. Themps_probabilities
sampling method be still used by setting the custom option valuemps_sample_measure_algorithm="mps_probabilities"
.
IBM Q Provider 0.16.0¶
No change
Qiskit 0.29.1¶
Terra 0.18.2¶
Bug Fixes¶
-
Fixed an issue with the
assemble()
function when called with thebackend
kwarg set and theparametric_pulses
kwarg was set to an empty list the output qobj would contain theparametric_pulses
setting from the given backend'sBackendConfiguration
instead of the expected empty list. Fixed #6898 -
The Matplotlib circuit drawer will no longer duplicate drawings when using
ipykernel>=6.0.0
. Fixes #6889.
Aqua 0.9.5¶
Bug Fixes¶
-
Fixed a handling error in the Yahoo provider when only one ticker is entered. Added exception error if no ticker is entered. Limit yfinance to >=0.1.62 as previous versions have a JSON decoder error.
IBM Q Provider 0.16.0¶
No change
Qiskit 0.29.0¶
Terra 0.18.1¶
Prelude¶
This bugfix release fixes a few minor issues and regressions in the 0.18.0 release. There is also a minor change to how pip
handles the [all]
extra when installing qiskit-terra
directly, compared to 0.18.0.
Upgrade Notes¶
-
pip install qiskit-terra[all]
will no longer attempt to install thebip-mapper
extra. This is because the dependencycplex
is not well supported on the range of Python versions and OSes that Terra supports, and a failed extra dependency would fail the entire package resolution. If you are using Python 3.7 or 3.8 and are on Linux-x64 or -ppc64le, macOS-x64 or Windows-x64 you should be able to installqiskit-terra[bip-mapper]
explicitly, if desired, while other combinations of OS, platform architectures and Python versions will likely fail.
Bug Fixes¶
-
Fixed an issue where the
QuantumInstance
class would potentially try to use theCompleteMeasFitter
class before it was imported resulting in an error. Fixed #6774 -
Fixed the missing Linux aarch64 wheels which were not published for the 0.18.0 release. They should now continue to be built as expected for all future releases.
-
Fixed an issue with the mock backends located in
qiskit.test.mock
where in some situations (mainly fake backends with storedBackendProperties
running aQuantumCircuit
withqiskit-aer
installed) passing run time options to therun()
method of a fake backend object would not actually be passed to the simulator underlying therun()
method and not have any effect. Fixed #6741 -
Fix a bug in
EvolvedOperatorAnsatz
when the global phase is 0 (such as forQAOAAnsatz
) but was still aParameterExpression
. -
Fixed an issue with the
settings
attribute ofQNSPSA
, which was missing thefidelity
argument from the output. This is now correctly included in the attribute's output. -
Fixed an issue with the
subgraph()
method of theCouplingMap
class where it would incorrectly add nodes to the outputCouplingMap
object when thenodelist
argument contained a non-contiguous list of qubit indices. This has been fixed so regardless of the input indices innodelist
the outputCouplingMap
will only contained the specified nodes reindexed starting at 0. Fixes #6736 -
Previously,
Optimize1qGatesDecomposition
failed to properly optimize one qubit gates that are sufficiently close to the identity matrix. This was fixed so that any gates that differ from the identity by less than 1e-15 are removed. -
Fixed the generation and loading of QPY files with
qiskit.circuit.qpy_serialization.dump()
andqiskit.circuit.qpy_serialization.load()
forQuantumCircuit
objects that contain instructions with classical conditions on a singleClbit
instead of aClassicalRegister
. While the use of singleClbit
conditions is not yet fully supported, if you were using them in a circuit they are now correctly serialized by QPY.
IBM Q Provider 0.16.0¶
Upgrade Notes¶
-
IBMExperimentService
is updated to work with the newqiskit-experiments
. As a result, the syntax of the experiment service is drastically changed. This change, however, takes the experiment service out of beta mode, and future changes will provide backward compatibility according to Qiskit deprecation policy. -
qiskit.providers.ibmq.runtime.utils.RuntimeEncoder
now convert a callable object toNone
, since callables are not JSON serializable. -
qiskit.providers.ibmq.IBMQBackend.run()
no longer accepts validate_qobj as a parameter. If you were relying on this schema validation you should pull the schemas from the Qiskit/ibm-quantum-schemas and directly validate your payloads with that.
Qiskit 0.28.0¶
Terra 0.18.0¶
Prelude¶
This release includes many new features and bug fixes. The highlights of this release are the introduction of two new transpiler passes, BIPMapping
and DynamicalDecoupling
, which when combined with the new pulse_optimize
kwarg on the UnitarySynthesis
pass enables recreating the Quantum Volume 64 results using the techniques described in: https://arxiv.org/abs/2008.08571. These new transpiler passes and options and are also generally applicable to optimizing any circuit.
New Features¶
-
The
measurement_error_mitgation
kwarg for theQuantumInstance
constructor can now be set to theTensoredMeasFitter
class from qiskit-ignis in addition toCompleteMeasFitter
that was already supported. If you useTensoredMeasFitter
you will also be able to set the newmit_pattern
kwarg to specify the qubits on which to useTensoredMeasFitter
You can refer to the documentation formit_pattern
in theTensoredMeasFitter
documentation for the expected format. -
The decomposition methods for single-qubit gates, specified via the
basis
kwarg, inOneQubitEulerDecomposer
has been expanded to now also include the'ZSXX'
basis, for making use of direct \(X\) gate as well as \(\sqrt{X}\) gate. -
Added two new passes
AlignMeasures
andValidatePulseGates
to theqiskit.transpiler.passes
module. These passes are a hardware-aware optimization, and a validation routine that are used to manage alignment restrictions on time allocation of instructions for a backend.If a backend has a restriction on the alignment of
Measure
instructions (in terms of quantization in time), theAlignMeasures
pass is used to adjust delays in a scheduled circuit to ensure that anyMeasure
instructions in the circuit are aligned given the constraints of the backend. TheValidatePulseGates
pass is used to check if any custom pulse gates (gates that have a custom pulse definition in thecalibrations
attribute of aQuantumCircuit
object) are valid given an alignment constraint for the target backend.In the built-in
preset_passmangers
used by thetranspile()
function, these passes get automatically triggered if the alignment constraint, either via the dedicatedtiming_constraints
kwarg ontranspile()
or has antiming_constraints
attribute in theBackendConfiguration
object of the backend being targetted.The backends from IBM Quantum Services (accessible via the qiskit-ibmq-provider package) will provide the alignment information in the near future.
For example:
from qiskit import circuit , transpile from qiskit.test.mock import FakeArmonk backend = FakeArmonk () qc = circuit . QuantumCircuit ( 1 , 1 ) qc . x ( 0 ) qc . delay ( 110 , 0 , unit = "dt" ) qc . measure ( 0 , 0 ) qc . draw ( 'mpl' )
qct = transpile ( qc , backend , scheduling_method = 'alap' , timing_constraints = { 'acquire_alignment' : 16 }) qct . draw ( 'mpl' )
-
A new transpiler pass class
qiskit.transpiler.passes.BIPMapping
that tries to find the best layout and routing at once by solving a BIP (binary integer programming) problem as described in arXiv:2106.06446 has been added.The
BIPMapping
pass (named "mapping" to refer to "layout and routing") represents the mapping problem as a BIP (binary integer programming) problem and relies on CPLEX (cplex
) to solve the BIP problem. The dependent libraries including CPLEX can be installed along with qiskit-terra:pip install qiskit - terra [ bip - mapper ]
Since the free version of CPLEX can solve only small BIP problems, i.e. mapping of circuits with less than about 5 qubits, the paid version of CPLEX may be needed to map larger circuits.
The BIP mapper scales badly with respect to the number of qubits or gates. For example, it would not work with
coupling_map
beyond 10 qubits because the BIP solver (CPLEX) could not find any solution within the default time limit.Note that, if you want to fix physical qubits to be used in the mapping (e.g. running Quantum Volume (QV) circuits), you need to specify
coupling_map
which contains only the qubits to be used.Here is a minimal example code to build pass manager to transpile a QV circuit:
num_qubits = 4 # QV16 circ = QuantumVolume ( num_qubits = num_qubits ) backend = ... basis_gates = backend . configuration () . basis_gates coupling_map = CouplingMap . from_line ( num_qubits ) # supply your own coupling map def _not_mapped ( property_set ): return not property_set [ "is_swap_mapped" ] def _opt_control ( property_set ): return not property_set [ "depth_fixed_point" ] from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel pm = PassManager () # preparation pm . append ([ Unroll3qOrMore (), TrivialLayout ( coupling_map ), FullAncillaAllocation ( coupling_map ), EnlargeWithAncilla (), BarrierBeforeFinalMeasurements () ]) # mapping pm . append ( BIPMapping ( coupling_map )) pm . append ( CheckMap ( coupling_map )) pm . append ( Error ( msg = "BIP mapper failed to map" , action = "raise" ), condition = _not_mapped ) # post optimization pm . append ([ Depth (), FixedPoint ( "depth" ), Collect2qBlocks (), ConsolidateBlocks ( basis_gates = basis_gates ), UnitarySynthesis ( basis_gates ), Optimize1qGatesDecomposition ( basis_gates ), CommutativeCancellation (), UnrollCustomDefinitions ( sel , basis_gates ), BasisTranslator ( sel , basis_gates ) ], do_while = _opt_control ) transpile_circ = pm . run ( circ )
-
A new constructor method
initialize_from()
was added to theSchedule
andScheduleBlock
classes. This method initializes a new empty schedule which takes the attributes from other schedule. For example:sched = Schedule ( name = 'my_sched' ) new_sched = Schedule . initialize_from ( sched ) assert sched . name == new_sched . name
-
A new kwarg,
line_discipline
, has been added to thejob_monitor()
function. This kwarg enables changing the carriage return characters used in thejob_monitor
output. Theline_discipline
kwarg defaults to'\r'
, which is what was in use before. -
The abstract
Pulse
class (which is the parent class for classes such asWaveform
,Constant
, andGaussian
now has a new kwarg on the constructor,limit_amplitude
, which can be set toFalse
to disable the previously hard coded amplitude limit of1
. This can also be set as a class attribute directly to change the global default for a Pulse class. For example:from qiskit.pulse.library import Waveform # Change the default value of limit_amplitude to False Waveform . limit_amplitude = False wave = Waveform ( 2.0 * np . exp ( 1 j * 2 * np . pi * np . linspace ( 0 , 1 , 1000 )))
-
A new class,
PauliList
, has been added to theqiskit.quantum_info
module. This class is used to efficiently represent a list ofPauli
operators. This new class inherets from the same parent class as the existingPauliTable
(and therefore can be mostly used interchangeably), however it differs from thePauliTable
because theqiskit.quantum_info.PauliList
class can handle Z4 phases. -
Added a new transpiler pass,
RemoveBarriers
, toqiskit.transpiler.passes
. This pass is used to remove all barriers in a circuit. -
Add a new optimizer class,
SciPyOptimizer
, to theqiskit.algorithms.optimizers
module. This class is a simple wrapper class of thescipy.optimize.minimize
function (documentation) which enables the use of all optimization solvers and all parameters (e.g. callback) which are supported byscipy.optimize.minimize
. For example:from qiskit.algorithms.optimizers import SciPyOptimizer values = [] def callback ( x ): values . append ( x ) optimizer = SciPyOptimizer ( "BFGS" , options = { "maxiter" : 1000 }, callback = callback )
-
The
HoareOptimizer
pass has been improved so that it can now replace aControlledGate
in a circuit with with the base gate if all the control qubits are in the \(|1\rangle\) state. -
Added two new methods,
is_successor()
andis_predecessor()
, to theDAGCircuit
class. These functions are used to check if a node is either a successor or predecessor of another node on theDAGCircuit
. -
A new transpiler pass,
RZXCalibrationBuilderNoEcho
, was added to theqiskit.transpiler.passes
module. This pass is similar to the existingRZXCalibrationBuilder
in that it creates calibrations for anRZXGate(theta)
, howeverRZXCalibrationBuilderNoEcho
does this without inserting the echo pulses in the pulse schedule. This enables exposing the echo in the cross-resonance sequence as gates so that the transpiler can simplify them. TheRZXCalibrationBuilderNoEcho
pass only supports the hardware-native direction of theCXGate
. -
A new kwarg,
wrap
, has been added to thecompose()
method ofQuantumCircuit
. This enables choosing whether composed circuits should be wrapped into an instruction or not. By default this isFalse
, i.e. no wrapping. For example:from qiskit import QuantumCircuit circuit = QuantumCircuit ( 2 ) circuit . h ([ 0 , 1 ]) other = QuantumCircuit ( 2 ) other . x ([ 0 , 1 ]) print ( circuit . compose ( other , wrap = True )) # wrapped print ( circuit . compose ( other , wrap = False )) # not wrapped
┌───┐┌──────────────┐ q_0: ┤ H ├┤0 ├ ├───┤│ circuit-114 │ q_1: ┤ H ├┤1 ├ └───┘└──────────────┘ ┌───┐┌───┐ q_0: ┤ H ├┤ X ├ ├───┤├───┤ q_1: ┤ H ├┤ X ├ └───┘└───┘
-
A new attribute,
control_channels
, has been added to thePulseBackendConfiguration
class. This attribute represents the control channels on a backend as a mapping of qubits to a list ofControlChannel
objects. -
A new kwarg,
epsilon
, has been added to the constructor for theIsometry
class and the correspondingQuantumCircuit
methodisometry()
. This kwarg enables optionally setting the epsilon tolerance used by anIsometry
gate. For example:import numpy as np from qiskit import QuantumRegister , QuantumCircuit tolerance = 1e-8 iso = np . eye ( 2 , 2 ) num_q_output = int ( np . log2 ( iso . shape [ 0 ])) num_q_input = int ( np . log2 ( iso . shape [ 1 ])) q = QuantumRegister ( num_q_output ) qc = QuantumCircuit ( q ) qc . isometry ( iso , q [: num_q_input ], q [ num_q_input :], epsilon = tolerance )
-
Added a transpiler pass,
DynamicalDecoupling
, toqiskit.transpiler.passes
for inserting dynamical decoupling sequences in idle periods of a circuit (after mapping to physical qubits and scheduling). The pass allows control over the sequence of DD gates, the spacing between them, and the qubits to apply on. For example:from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import XGate from qiskit.transpiler import PassManager , InstructionDurations from qiskit.transpiler.passes import ALAPSchedule , DynamicalDecoupling from qiskit.visualization import timeline_drawer circ = QuantumCircuit ( 4 ) circ . h ( 0 ) circ . cx ( 0 , 1 ) circ . cx ( 1 , 2 ) circ . cx ( 2 , 3 ) circ . measure_all () durations = InstructionDurations ( [( "h" , 0 , 50 ), ( "cx" , [ 0 , 1 ], 700 ), ( "reset" , None , 10 ), ( "cx" , [ 1 , 2 ], 200 ), ( "cx" , [ 2 , 3 ], 300 ), ( "x" , None , 50 ), ( "measure" , None , 1000 )] ) dd_sequence = [ XGate (), XGate ()] pm = PassManager ([ ALAPSchedule ( durations ), DynamicalDecoupling ( durations , dd_sequence )]) circ_dd = pm . run ( circ ) timeline_drawer ( circ_dd )
-
The
QuantumCircuit
methodqasm()
has a new kwarg,encoding
, which can be used to optionally set the character encoding of an output QASM file generated by the function. This can be set to any valid codec or alias string from the Python standard library's codec module. -
Added a new class,
EvolvedOperatorAnsatz
, to theqiskit.circuit.library
module. This library circuit, which had previously been located in Qiskit Nature , can be used to construct ansatz circuits that consist of time-evolved operators, where the evolution time is a variational parameter. Examples of such ansatz circuits includeUCCSD
class in thechemistry
module of Qiskit Nature or theQAOAAnsatz
class. -
A new fake backend class is available under
qiskit.test.mock
for theibmq_guadalupe
backend. As with the other fake backends, this includes a snapshot of calibration data (i.e.backend.defaults()
) and error data (i.e.backend.properties()
) taken from the real system, and can be used for local testing, compilation and simulation. -
A new method
children()
for theSchedule
class has been added. This method is used to return the child schedule components of theSchedule
object as a tuple. It returns nested schedules without flattening. This method is equivalent to the private_children()
method but has a public and stable interface. -
A new optimizer class,
GradientDescent
, has been added to theqiskit.algorithms.optimizers
module. This optimizer class implements a standard gradient descent optimization algorithm for use with quantum variational algorithms, such asVQE
. For a detailed description and examples on how to use this class, please refer to theGradientDescent
class documentation. -
A new optimizer class,
QNSPSA
, has been added to theqiskit.algorithms.optimizers
module. This class implements the Quantum Natural SPSA (QN-SPSA) algorithm, a generalization of the 2-SPSA algorithm, and estimates the Quantum Fisher Information Matrix instead of the Hessian to obtain a stochastic estimate of the Quantum Natural Gradient. For examples on how to use this new optimizer refer to theQNSPSA
class documentation. -
A new kwarg,
second_order
, has been added to the constructor of theSPSA
class in theqiskit.algorithms.optimizers
module. When set toTrue
this enables using second-order SPSA. Second order SPSA, or 2-SPSA, is an extension of the ordinary SPSA algorithm that enables estimating the Hessian alongside the gradient, which is used to precondition the gradient before the parameter update step. As a second-order method, this tries to improve convergence of SPSA. For examples on how to use this option refer to theSPSA
class documentation. -
When using the
latex
orlatex_source
output mode ofcircuit_drawer()
or thedraw()
ofQuantumCircuit
thestyle
kwarg can now be used just as with thempl
output formatting. However, unlike thempl
output mode only thedisplaytext
field will be used when using thelatex
orlatex_source
output modes (because neither supports color). -
When using the
mpl
orlatex
output methods for thecircuit_drawer()
function or thedraw()
ofQuantumCircuit
, you can now use math mode formatting for text and set color formatting (mpl
only) by setting thestyle
kwarg as a dict with a user-generated name or label. For example, to add subscripts and to change a gate color:from qiskit import QuantumCircuit from qiskit.circuit.library import HGate qc = QuantumCircuit ( 3 ) qc . append ( HGate ( label = 'h1' ), [ 0 ]) qc . append ( HGate ( label = 'h2' ), [ 1 ]) qc . append ( HGate ( label = 'h3' ), [ 2 ]) qc . draw ( 'mpl' , style = { 'displaytext' : { 'h1' : 'H_1' , 'h2' : 'H_2' , 'h3' : 'H_3' }, 'displaycolor' : { 'h2' : ( '#EEDD00' , '#FF0000' )}})
-
Added three new classes,
CDKMRippleCarryAdder
,ClassicalAdder
andDraperQFTAdder
, to theqiskit.circuit.library
module. These new circuit classes are used to perform classical addition of two equally-sized qubit registers. For two registers \(|a\rangle_n\) and \(|b\rangle_n\) on \(n\) qubits, the three new classes perform the operation:\[|a\rangle_n |b\rangle_n \mapsto |a\rangle_n |a + b\rangle_{n + 1}.\]
For example:
from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import CDKMRippleCarryAdder from qiskit.quantum_info import Statevector # a encodes |01> = 1 a = QuantumCircuit ( 2 ) a . x ( 0 ) # b encodes |10> = 2 b = QuantumCircuit ( 2 ) b . x ( 1 ) # adder on 2-bit numbers adder = CDKMRippleCarryAdder ( 2 ) # add the state preparations to the front of the circuit adder . compose ( a , [ 0 , 1 ], inplace = True , front = True ) adder . compose ( b , [ 2 , 3 ], inplace = True , front = True ) # simulate and get the state of all qubits sv = Statevector ( adder ) counts = sv . probabilities_dict () state = list ( counts . keys ())[ 0 ] # we only have a single state # skip the input carry (first bit) and the register |a> (last two bits) result = state [ 1 : - 2 ] print ( result ) # '011' = 3 = 1 + 2
-
Added two new classes,
RGQFTMultiplier
andHRSCumulativeMultiplier
, to theqiskit.circuit.library
module. These classes are used to perform classical multiplication of two equally-sized qubit registers. For two registers \(|a\rangle_n\) and \(|b\rangle_n\) on \(n\) qubits, the two new classes perform the operation\[|a\rangle_n |b\rangle_n |0\rangle_{2n} \mapsto |a\rangle_n |b\rangle_n |a \cdot b\rangle_{2n}.\]
For example:
from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import RGQFTMultiplier from qiskit.quantum_info import Statevector num_state_qubits = 2 # a encodes |11> = 3 a = QuantumCircuit ( num_state_qubits ) a . x ( range ( num_state_qubits )) # b encodes |11> = 3 b = QuantumCircuit ( num_state_qubits ) b . x ( range ( num_state_qubits )) # multiplier on 2-bit numbers multiplier = RGQFTMultiplier ( num_state_qubits ) # add the state preparations to the front of the circuit multiplier . compose ( a , [ 0 , 1 ], inplace = True , front = True ) multiplier . compose ( b , [ 2 , 3 ], inplace = True , front = True ) # simulate and get the state of all qubits sv = Statevector ( multiplier ) counts = sv . probabilities_dict ( decimals = 10 ) state = list ( counts . keys ())[ 0 ] # we only have a single state # skip both input registers result = state [: - 2 * num_state_qubits ] print ( result ) # '1001' = 9 = 3 * 3
-
The
Delay
class now can accept aParameterExpression
orParameter
value for theduration
kwarg on its constructor and for itsduration
attribute.For example:
idle_dur = Parameter ( 't' ) qc = QuantumCircuit ( 1 , 1 ) qc . x ( 0 ) qc . delay ( idle_dur , 0 , 'us' ) qc . measure ( 0 , 0 ) print ( qc ) # parameterized delay in us (micro seconds) # assign before transpilation assigned = qc . assign_parameters ({ idle_dur : 0.1 }) print ( assigned ) # delay in us transpiled = transpile ( assigned , some_backend_with_dt ) print ( transpiled ) # delay in dt # assign after transpilation transpiled = transpile ( qc , some_backend_with_dt ) print ( transpiled ) # parameterized delay in dt assigned = transpiled . assign_parameters ({ idle_dur : 0.1 }) print ( assigned ) # delay in dt
-
A new binary serialization format, QPY, has been introduced. It is designed to be a fast binary serialization format that is backwards compatible (QPY files generated with older versions of Qiskit can be loaded by newer versions of Qiskit) that is native to Qiskit. The QPY serialization tooling is available via the
qiskit.circuit.qpy_serialization
module. For example, to generate a QPY file:from datetime import datetime from qiskit.circuit import QuantumCircuit from qiskit.circuit import qpy_serialization qc = QuantumCircuit ( 2 , metadata = { 'created_at' : datetime . utcnow () . isoformat ()} ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc . measure_all () circuits = [ qc ] * 5 with open ( 'five_bells.qpy' , 'wb' ) as qpy_file : qpy_serialization . dump ( circuits , qpy_file )
Then the five circuits saved in the QPY file can be loaded with:
from qiskit.circuit.qpy_serialization with open ( 'five_bells.qpy' , 'rb' ) as qpy_file : circuits = qpy_serialization . load ( qpy_file )
The QPY file format specification is available in the module documentation.
-
The
TwoQubitBasisDecomposer
class has been updated to perform pulse optimal decompositions for a basis with CX, √X, and virtual Rz gates as described in https://arxiv.org/pdf/2008.08571. Pulse optimal here means that the duration of gates between the CX gates of the decomposition is reduced in exchange for possibly more local gates before or after all the CX gates such that, when composed into a circuit, there is the possibility of single qubit compression with neighboring gates reducing the overall sequence duration.A new keyword argument,
`pulse_optimize
, has been added to the constructor forTwoQubitBasisDecomposer
to control this:-
None
: Attempt pulse optimal decomposition. If a pulse optimal decomposition is unknown for the basis of the decomposer, drop back to the standard decomposition without warning. This is the default setting. -
True
: Attempt pulse optimal decomposition. If a pulse optimal decomposition is unknown for the basis of the decomposer, raise QiskitError. -
False
: Do not attempt pulse optimal decomposition.
For example:
from qiskit.quantum_info import TwoQubitBasisDecomposer from qiskit.circuit.library import CXGate from qiskit.quantum_info import random_unitary unitary_matrix = random_unitary ( 4 ) decomposer = TwoQubitBasisDecomposer ( CXGate (), euler_basis = "ZSX" , pulse_optimize = True ) circuit = decomposer ( unitary_matrix )
-
-
The transpiler pass
UnitarySynthesis
located inqiskit.transpiler.passes
has been updated to support performing pulse optimal decomposition. This is done primarily with the thepulse_optimize
keyword argument which was added to the constructor and used to control whether pulse optimal synthesis is performed. The behavior of this kwarg mirrors thepulse_optimize
kwarg in theTwoQubitBasisDecomposer
class's constructor. Additionally, the constructor has another new keyword argument,synth_gates
, which is used to specify the list of gate names over which synthesis should be attempted. IfNone
andpulse_optimize
isFalse
orNone
, use"unitary"
. If None and pulse_optimize isTrue
, use"unitary"
and"swap"
. Since the direction of the CX gate in the synthesis is arbitrary, another keyword argument,natural_direction
, is added to consider first a coupling map and thenCXGate
durations in choosing for which direction of CX to generate the synthesis.from qiskit.circuit import QuantumCircuit from qiskit.transpiler import PassManager , CouplingMap from qiskit.transpiler.passes import TrivialLayout , UnitarySynthesis from qiskit.test.mock import FakeVigo from qiskit.quantum_info.random import random_unitary backend = FakeVigo () conf = backend . configuration () coupling_map = CouplingMap ( conf . coupling_map ) triv_layout_pass = TrivialLayout ( coupling_map ) circ = QuantumCircuit ( 2 ) circ . unitary ( random_unitary ( 4 ), [ 0 , 1 ]) unisynth_pass = UnitarySynthesis ( basis_gates = conf . basis_gates , coupling_map = None , backend_props = backend . properties (), pulse_optimize = True , natural_direction = True , synth_gates = [ 'unitary' ]) pm = PassManager ([ triv_layout_pass , unisynth_pass ]) optimal_circ = pm . run ( circ )
-
A new basis option,
'XZX'
, was added for thebasis
argumentOneQubitEulerDecomposer
class. -
Added a new method,
get_instructions()
, was added to theQuantumCircuit
class. This method is used to return allInstruction
objects in the circuit which have aname
that matches the providedname
argument along with its associatedqargs
andcargs
lists ofQubit
andClbit
objects. -
A new optional extra
all
has been added to the qiskit-terra package. This enables installing all the optional requirements with a single extra, for example:pip install 'qiskit-terra[all]'
, Previously, it was necessary to list all the extras individually to install all the optional dependencies simultaneously. -
Added two new classes
ProbDistribution
andQuasiDistribution
for dealing with probability distributions and quasiprobability distributions respectively. These objects both are dictionary subclasses that add additional methods for working with probability and quasiprobability distributions. -
Added a new
settings
property to theOptimizer
abstract base class that all the optimizer classes in theqiskit.algorithms.optimizers
module are based on. This property will return a Python dictionary of the settings for the optimizer that can be used to instantiate another instance of the same optimizer class. For example:from qiskit.algorithms.optimizers import GradientDescent optimizer = GradientDescent ( maxiter = 10 , learning_rate = 0.01 ) settings = optimizer . settings new_optimizer = GradientDescent ( ** settings )
The
settings
dictionary is also potentially useful for serializing optimizer objects using JSON or another serialization format. -
A new function,
set_config()
, has been added to theqiskit.user_config
module. This function enables setting values in a user config from the Qiskit API. For example:from qiskit.user_config import set_config set_config ( "circuit_drawer" , "mpl" , section = "default" , file = "settings.conf" )
which will result in adding a value of
circuit_drawer = mpl
to thedefault
section in thesettings.conf
file.If no
file_path
argument is specified, the currently used path to the user config file (either the value of theQISKIT_SETTINGS
environment variable if set or the default location~/.qiskit/settings.conf
) will be updated. However, changes to the existing config file will not be reflected in the current session since the config file is parsed at import time. -
Added a new state class,
StabilizerState
, to theqiskit.quantum_info
module. This class represents a stabilizer simulator state using the convention from Aaronson and Gottesman (2004). -
Two new options,
'value'
and'value_desc'
were added to thesort
kwarg of theqiskit.visualization.plot_histogram()
function. Whensort
is set to either of these options the output visualization will sort the x axis based on the maximum probability for each bitstring. For example:from qiskit.visualization import plot_histogram counts = { '000' : 5 , '001' : 25 , '010' : 125 , '011' : 625 , '100' : 3125 , '101' : 15625 , '110' : 78125 , '111' : 390625 , } plot_histogram ( counts , sort = 'value' )
Known Issues¶
-
When running
parallel_map()
(and functions that internally callparallel_map()
such astranspile()
andassemble()
) on Python 3.9 withQISKIT_PARALLEL
set to True in some scenarios it is possible for the program to deadlock and never finish running. To avoid this from happening the default for Python 3.9 was changed to not run in parallel, but ifQISKIT_PARALLEL
is explicitly enabled then this can still occur.
Upgrade Notes¶
-
The minimum version of the retworkx dependency was increased to version 0.9.0. This was done to use new APIs introduced in that release which improved the performance of some transpiler passes.
-
The default value for
QISKIT_PARALLEL
on Python 3.9 environments has changed toFalse
, this means that when running on Python 3.9 by default multiprocessing will not be used. This was done to avoid a potential deadlock/hanging issue that can occur when running multiprocessing on Python 3.9 (see the known issues section for more detail). It is still possible to manual enable it by explicitly setting theQISKIT_PARALLEL
environment variable toTRUE
. -
The existing fake backend classes in
qiskit.test.mock
now strictly implement theBackendV1
interface. This means that if you were manually constructingQasmQobj
orPulseQobj
object for use with therun()
method this will no longer work. Therun()
method only acceptsQuantumCircuit
orSchedule
objects now. This was necessary to enable testing of new backends implemented without qobj which previously did not have any testing inside qiskit terra. If you need to leverage the fake backends withQasmQobj
orPulseQobj
new fake legacy backend objects were added to explicitly test the legacy providers interface. This will be removed after the legacy interface is deprecated and removed. Moving forward new fake backends will only implement theBackendV1
interface and will not add new legacy backend classes for new fake backends. -
When creating a
Pauli
object with an invalid string label, aQiskitError
is now raised. This is a change from previous releases which would raise anAttributeError
on an invalid string label. This change was made to ensure the error message is more informative and distinct from a genericAttributeError
. -
The output program representation from the pulse builder (
qiskit.pulse.builder.build()
) has changed from aSchedule
to aScheduleBlock
. This new representation disables some timing related operations such as shift and insert. However, this enables parameterized instruction durations within the builder context. For example:from qiskit import pulse from qiskit.circuit import Parameter dur = Parameter ( 'duration' ) with pulse . build () as sched : with pulse . align_sequential (): pulse . delay ( dur , pulse . DriveChannel ( 1 )) pulse . play ( pulse . Gaussian ( dur , 0.1 , dur / 4 ), pulse . DriveChannel ( 0 )) assigned0 = sched . assign_parameters ({ dur : 100 }) assigned1 = sched . assign_parameters ({ dur : 200 })
You can directly pass the duration-assigned schedules to the assembler (or backend), or you can attach them to your quantum circuit as pulse gates.
-
The tweedledum library which was previously an optional dependency has been made a requirement. This was done because of the wide use of the
PhaseOracle
(which depends on having tweedledum installed) with several algorithms fromqiskit.algorithms
. -
The optional extra
full-featured-simulators
which could previously used to installqiskit-aer
with something likepip install qiskit-terra[full-featured-simulators]
has been removed from the qiskit-terra package. If this was being used to installqiskit-aer
withqiskit-terra
instead you should rely on the qiskit metapackage or just install qiskit-terra and qiskit-aer together withpip install qiskit-terra qiskit-aer
. -
A new requirement symengine has been added for Linux (on x86_64, aarch64, and ppc64le) and macOS users (x86_64 and arm64). It is an optional dependency on Windows (and available on PyPi as a precompiled package for 64bit Windows) and other architectures. If it is installed it provides significantly improved performance for the evaluation of
Parameter
andParameterExpression
objects. -
All library circuit classes, i.e. all
QuantumCircuit
derived classes inqiskit.circuit.library
, are now wrapped in aInstruction
(orGate
, if they are unitary). For example, importing and drawing theQFT
circuit:before looked like
┌───┐ q_0: ────────────────────■────────■───────┤ H ├─X─ ┌───┐ │ │P(π/2) └───┘ │ q_1: ──────■───────┤ H ├─┼────────■─────────────┼─ ┌───┐ │P(π/2) └───┘ │P(π/4) │ q_2: ┤ H ├─■─────────────■──────────────────────X─ └───┘
and now looks like
┌──────┐ q_0: ┤0 ├ │ │ q_1: ┤1 QFT ├ │ │ q_2: ┤2 ├ └──────┘
To obtain the old circuit, you can call the
decompose()
method on the circuitThis change was primarily made for consistency as before this release some circuit classes in
qiskit.circuit.library
were previously wrapped in anInstruction
orGate
but not all.
Deprecation Notes¶
-
The class
qiskit.exceptions.QiskitIndexError
is deprecated and will be removed in a future release. This exception was not actively being used by anything in Qiskit, if you were using it you can create a custom exception class to replace it. -
The kwargs
epsilon
andfactr
for theqiskit.algorithms.optimizers.L_BFGS_B
constructor andfactr
kwarg of theP_BFGS
optimizer class are deprecated and will be removed in a future release. Instead, please use theeps
karg instead ofepsilon
. Thefactr
kwarg is replaced withftol
. The relationship between the two isftol = factr * numpy.finfo(float).eps
. This change was made to be consistent with the usage of thescipy.optimize.minimize
functions'L-BFGS-B'
method. See the:scipy.optimize.minimize(method='L-BFGS-B')
documentation for more information on how these new parameters are used. -
The legacy providers interface, which consisted of the
qiskit.providers.BaseBackend
,qiskit.providers.BaseJob
, andqiskit.providers.BaseProvider
abstract classes, has been deprecated and will be removed in a future release. Instead you should use the versioned interface, which the current abstract class versions areqiskit.providers.BackendV1
,qiskit.providers.JobV1
, andqiskit.providers.ProviderV1
. The V1 objects are mostly backwards compatible to ease migration from the legacy interface to the versioned one. However, expect future versions of the abstract interfaces to diverge more. You can refer to theqiskit.providers
documentation for more high level details about the versioned interface. -
The
condition
kwarg to theDAGDepNode
constructor along with the correspondingcondition
attribute of theDAGDepNode
have been deprecated and will be removed in a future release. Instead, you can access thecondition
of aDAGDepNode
if the node is of typeop
, by usingDAGDepNode.op.condition
. -
The
condition
attribute of theDAGNode
class has been deprecated and will be removed in a future release. Instead, you can access thecondition
of aDAGNode
object if the node is of typeop
, by usingDAGNode.op.condition
. -
The pulse builder (
qiskit.pulse.builder.build()
) syntaxqiskit.pulse.builder.inline()
is deprecated and will be removed in a future release. Instead of using this context, you can just remove alignment contexts within the inline context. -
The pulse builder (
qiskit.pulse.builder.build()
) syntaxqiskit.pulse.builder.pad()
is deprecated and will be removed in a future release. This was done because theScheduleBlock
now being returned by the pulse builder doesn't support the.insert
method (and there is no insert syntax in the builder). The use of timeslot placeholders to block the insertion of other instructions is no longer necessary.
Bug Fixes¶
-
The
OneQubitEulerDecomposer
andTwoQubitBasisDecomposer
classes for one and two qubit gate synthesis have been improved to tighten up tolerances, improved repeatability and simplification, and fix several global-phase-tracking bugs. -
Fixed an issue in the assignment of the
name
attribute toGate
generated by multiple calls to theinverse`()
method. Prior to this fix when theinverse`()
was called it would unconditionally append_dg
on each call to inverse. This has been corrected so on a second call ofinverse`()
the_dg
suffix is now removed. -
Fixes the triviality check conditions of
CZGate
,CRZGate
,CU1Gate
andMCU1Gate
in theHoareOptimizer
pass. Previously, in some cases the optimizer would remove these gates breaking the semantic equivalence of the transformation. -
Fixed an issue when converting a
ListOp
object ofPauliSumOp
objects usingPauliExpectation
orAerPauliExpectation
. Previously, it would raise a warning about it converting to a Pauli representation which is potentially expensive. This has been fixed by instead of internally converting theListOp
to aSummedOp
ofPauliOp
objects, it now creates aPauliSumOp
which is more efficient. Fixed #6159 -
Fixed an issue with the
NLocal
class in theqiskit.circuit.library
module where it wouldn't properly raise an exception at object initialization if an invalid type was used for thereps
kwarg which would result in an unexpected runtime error later. ATypeError
will now be properly raised if thereps
kwarg is not anint
value. Fixed #6515 -
Fixed an issue where the
TwoLocal
class in theqiskit.circuit.library
module did not accept numpy integer types (e.g.numpy.int32
,numpy.int64
, etc) as a valid input for theentanglement
kwarg. Fixed #6455 -
When loading an OpenQASM2 file or string with the
from_qasm_file()
orfrom_qasm_str()
constructors for theQuantumCircuit
class, if the OpenQASM2 circuit contains an instruction with the namedelay
this will be mapped to aqiskit.circuit.Delay
instruction. For example:from qiskit import QuantumCircuit qasm = """OPENQASM 2.0; include "qelib1.inc"; opaque delay(time) q; qreg q[1]; delay(172) q[0]; u3(0.1,0.2,0.3) q[0]; """ circuit = QuantumCircuit . from_qasm_str ( qasm ) circuit . draw ()
┌────────────────┐┌─────────────────┐ q: ┤ Delay(172[dt]) ├┤ U3(0.1,0.2,0.3) ├ └────────────────┘└─────────────────┘
Fixed #6510
-
Fixed an issue with addition between
PauliSumOp
objects that hadParameterExpression
coefficients. Previously this would result in aQiskitError
exception being raised because the addition of theParameterExpression
was not handled correctly. This has been fixed so that addition can be performed betweenPauliSumOp
objects withParameterExpression
coefficients. -
Fixed an issue with the initialization of the
AmplificationProblem
class. Theis_good_state
kwarg was a required field but incorrectly being treated as optional (and documented as such). This has been fixed and also updated so unless the inputoracle
is aPhaseOracle
object (which provides it's on evaluation method) the field is required and will raise aTypeError
when constructed withoutis_good_state
. -
Fixed an issue where adding a control to a
ControlledGate
with open controls would unset the inner open controls. Fixes #5857 -
Fixed an issue with the
convert()
method of thePauliExpectation
class where calling it on an operator that was non-Hermitian would return an incorrect result. Fixed #6307 -
Fixed an issue with the
qiskit.pulse.transforms.inline_subroutines()
function which would previously incorrectly not remove all the nested components when called on nested schedules. Fixed #6321 -
Fixed an issue when passing a partially bound callable created with the Python standard library's
functools.partial()
function as theschedule
kwarg to theadd()
method of theInstructionScheduleMap
class, which would previously result in an error. Fixed #6278 -
Fixed an issue with the
PiecewiseChebyshev
when setting thebreakpoints
toNone
on an existing object was incorrectly being treated as a breakpoint. This has been corrected so that when it is set toNone
this will switch back to the default behavior of approximating over the full interval. Fixed #6198 -
Fixed an issue with the
num_connected_components()
method ofQuantumCircuit
which was returning the incorrect number of components when the circuit contains two or more gates conditioned on classical registers. Fixed #6477 -
Fixed an issue with the
qiskit.opflow.expectations
module where coefficients of a statefunction were not being multiplied correctly. This also fixed the calculations of Gradients and QFIs when using thePauliExpectation
orAerPauliExpectation
classes. For example, previously:from qiskit.opflow import StateFn , I , One exp = ~ StateFn ( I ) @ ( 2 * One )
evaluated to
2
forAerPauliExpectation
and to4
for other expectation converters. Since~StateFn(I) @ (2 * One)
is a shorthand notation for~(2 * One) @ I @ (2 * One)
, the now correct coefficient of4
is returned for all expectation converters. Fixed #6497 -
Fixed the bug that caused
to_circuit()
to fail whenPauliOp
had a phase. At the same time, it was made more efficient to usePauliGate
. -
Fixed an issue where the QASM output generated by the
qasm()
method ofQuantumCircuit
for composite gates such asMCXGate
and its variants (MCXGrayCode
,MCXRecursive
, andMCXVChain
) would be incorrect. Now if aGate
in the circuit is not present inqelib1.inc
, its definition is added to the output QASM string. Fixed #4943 and #3945 -
Fixed an issue with the
circuit_drawer()
function anddraw()
method ofQuantumCircuit
. When using thempl
orlatex
output modes, with thecregbundle
kwarg set toFalse
and thereverse_bits
kwarg set toTrue
, the bits in the classical registers displayed in the same order as whenreverse_bits
was set toFalse
. -
Fixed an issue when using the
qiskit.extensions.Initialize
instruction which was not correctly setting the global phase of the synthesized definition when constructed. Fixed #5320 -
Fixed an issue where the bit-order in
qiskit.circuit.library.PhaseOracle.evaluate_bitstring()
did not agree with the order of the measured bitstring. This fix also affects the execution of theGrover
algorithm class if the oracle is specified as aPhaseOracle
, which now will now correctly identify the correct bitstring. Fixed #6314 -
Fixes a bug in
Optimize1qGatesDecomposition()
previously causing certain short sequences of gates to erroneously not be rewritten. -
Fixed an issue in the
qiskit.opflow.gradients.Gradient.gradient_wrapper()
method with the gradient calculation. Previously, if the operator was not diagonal an incorrect result would be returned in some situations. This has been fixed by using an expectation converter to ensure the result is always correct. -
Fixed an issue with the
circuit_drawer()
function anddraw()
method ofQuantumCircuit
with all output modes where it would incorrectly render a custom instruction that includes classical bits in some circumstances. Fixed #3201, #3202, and #6178 -
Fixed an issue in
circuit_drawer()
and thedraw()
method of theQuantumCircuit
class when using thempl
output mode, controlled-Z Gates were incorrectly drawn as asymmetrical. Fixed #5981 -
Fixed an issue with the
OptimizeSwapBeforeMeasure
transpiler pass where in some situations aSwapGate
that that contained a classical condition would be removed. Fixed #6192 -
Fixed an issue with the phase of the
qiskit.opflow.gradients.QFI
class when theqfi_method
is set tolin_comb_full
which caused the incorrect observable to be evaluated. -
Fixed an issue with
VQE
algorithm class when run with theL_BFGS_B
orP_BFGS
optimizer classes and gradients are used, the gradient was incorrectly passed as a numpy array instead of the expected list of floats resulting in an error. This has been resolved so you can use gradients withVQE
and theL_BFGS_B
orP_BFGS
optimizers.
Other Notes¶
-
The deprecation of the
parameters()
method for theInstruction
class has been reversed. This method was originally deprecated in the 0.17.0, but it is still necessary for several applications, including when running calibration experiments. This method will continue to be supported and will not be removed.
IBM Q Provider 0.15.0¶
Deprecation Notes¶
-
The
id
instruction has been deprecated on IBM hardware backends. Instead, please use thedelay
instruction which implements variable-length delays, specified in units ofdt
. When running a circuit containing anid
instruction, a warning will be raised on job submission and anyid
instructions in the job will be automatically replaced with their equivalentdelay
instruction.
Qiskit 0.27.0¶
Aqua 0.9.2¶
Bug Fixes¶
-
Removed version caps from the requirements list to enable installing with newer versions of dependencies.
IBM Q Provider 0.14.0¶
New Features¶
-
You can now use the
qiskit.providers.ibmq.runtime.RuntimeJob.logs()
method to retrieve job logs. Note that logs are only available after the job finishes. -
A new backend configuration attribute
input_allowed
now tells you the types of input supported by the backend. Valid input types arejob
, which means circuit jobs, andruntime
, which means Qiskit Runtime.You can also use
input_allowed
in backend filtering. For example:from qiskit import IBMQ provider = IBMQ . load_account () # Get a list of all backends that support runtime. runtime_backends = provider . backends ( input_allowed = 'runtime' )
Upgrade Notes¶
-
qiskit-ibmq-provider
now uses a new packagewebsocket-client
as its websocket client, and packageswebsockets
andnest-asyncio
are no longer required.setup.py
andrequirements.txt
have been updated accordingly.
Bug Fixes¶
-
Fixes the issue that uses
shots=1
instead of the documented default when noshots
is specified forrun_circuits()
. -
Fixes the issue wherein a
QiskitBackendNotFoundError
exception is raised when retrieving a runtime job that was submitted using a different provider than the one used for retrieval. -
Streaming runtime program interim results with proxies is now supported. You can specify the proxies to use when enabling the account as usual, for example:
from qiskit import IBMQ proxies = { 'urls' : { 'https://127.0.0.1:8085' }} provider = IBMQ . enable_account ( API_TOKEN , proxies = proxies )
Qiskit 0.26.1¶
Terra 0.17.4¶
Bug Fixes¶
-
Fixed an issue with the
QuantumInstance
withBackendV1
backends with the`max_experiments
attribute set to a value less than the number of circuits to run. Previously theQuantumInstance
would not correctly split the circuits to run into separate jobs, which has been corrected.
IBM Q Provider 0.13.1¶
No change
Qiskit 0.26.0¶
Terra 0.17.3¶
Prelude¶
This release includes 2 new classes, ProbDistribution
and QuasiDistribution
, which were needed for compatibility with the recent qiskit-ibmq-provider release's beta support for the qiskit-runtime. These were only added for compatibility with that new feature in the qiskit-ibmq-provider release and the API for these classes is considered experimental and not considered stable for the 0.17.x release series. The interface may change when 0.18.0 is released in the future.
Bug Fixes¶
-
Fixed an issue in
plot_histogram()
function where aValueError
would be raised when the function run on distributions with unequal lengths.
IBM Q Provider 0.13.1¶
Prelude¶
This release introduces a new feature Qiskit Runtime Service
. Qiskit Runtime is a new architecture offered by IBM Quantum that significantly reduces waiting time during computational iterations. You can execute your experiments near the quantum hardware, without the interactions of multiple layers of classical and quantum hardware slowing it down.
Qiskit Runtime allows authorized users to upload their Qiskit quantum programs, which are Python code that takes certain inputs, performs quantum and maybe classical computation, and returns the processing results. The same or other authorized users can then invoke these quantum programs by simply passing in the required input parameters.
Note that Qiskit Runtime is currently in private beta for select account but will be released to the public in the near future.
New Features¶
-
qiskit.providers.ibmq.experiment.analysis_result.AnalysisResult
now has an additionalverified
attribute which identifies if thequality
has been verified by a human. -
qiskit.providers.ibmq.experiment.Experiment
now has an additionalnotes
attribute which can be used to set notes on an experiment. -
This release introduces a new feature
Qiskit Runtime Service
. Qiskit Runtime is a new architecture that significantly reduces waiting time during computational iterations. This new service allows authorized users to upload their Qiskit quantum programs, which are Python code that takes certain inputs, performs quantum and maybe classical computation, and returns the processing results. The same or other authorized users can then invoke these quantum programs by simply passing in the required input parameters.An example of using this new service:
from qiskit import IBMQ provider = IBMQ . load_account () # Print all avaiable programs. provider . runtime . pprint_programs () # Prepare the inputs. See program documentation on input parameters. inputs = { ... } options = { "backend_name" : provider . backend . ibmq_montreal . name ()} job = provider . runtime . run ( program_id = "runtime-simple" , options = options , inputs = inputs ) # Check job status. print ( f "job status is { job . status () } " ) # Get job result. result = job . result ()
Upgrade Notes¶
-
The deprecated
Human Bad
,Computer Bad
,Computer Good
andHuman Good
enum values have been removed fromqiskit.providers.ibmq.experiment.constants.ResultQuality
. They are replaced withBad
andGood
values which should be used with theverified
attribute onqiskit.providers.ibmq.experiment.analysis_result.AnalysisResult
:Old Quality
New Quality
Verified
Human Bad
Bad
True
Computer Bad
Bad
False
Computer Good
Good
False
Human Good
Good
True
Furthermore, the
NO_INFORMATION
enum has been renamed toUNKNOWN
. -
The
qiskit.providers.ibmq.IBMQBackend.defaults()
method now always returns pulse defaults if they are available, regardless whether open pulse is enabled for the provider.
Bug Fixes¶
-
Fixes the issue wherein passing in a noise model when sending a job to an IBMQ simulator would raise a
TypeError
. Fixes #894
Other Notes¶
-
The
qiskit.providers.ibmq.experiment.analysis_result.AnalysisResult
fit
attribute is now optional.
Qiskit 0.25.4¶
Terra 0.17.2¶
Prelude¶
This is a bugfix release that fixes several issues from the 0.17.1 release. Most importantly this release fixes compatibility for the QuantumInstance
class when running on backends that are based on the BackendV1
abstract class. This fixes all the algorithms and applications built on qiskit.algorithms
or qiskit.opflow
when running on newer backends.
IBM Q Provider 0.12.3¶
No change
Qiskit 0.25.3¶
Aer 0.8.2¶
Bug Fixes¶
-
Fixes performance issue with how the
basis_gates
configuration attribute was set. Previously there were unintended side-effects to the backend class which could cause repeated simulation runtime to incrementally increase. Refer to #1229 <https://github.com/Qiskit/qiskit-aer/issues/1229> for more information and examples. -
Fixes a bug with the
"multiplexer"
simulator instruction where the order of target and control qubits was reversed to the order in the Qiskit instruction. -
Fixes a bug introduced in 0.8.0 where GPU simulations would allocate unneeded host memory in addition to the GPU memory.
-
Fixes a bug in the
stabilizer
simulator method of theQasmSimulator
andAerSimulator
where the expectation value for thesave_expectation_value
andsnapshot_expectation_value
could have the wrong sign for certainY
Pauli's.
IBM Q Provider 0.12.3¶
No change
Qiskit 0.25.2¶
IBM Q Provider 0.12.3¶
Other Notes¶
-
The
qiskit.providers.ibmq.experiment.analysis_result.AnalysisResult
fit
attribute is now optional.
Qiskit 0.25.1¶
Terra 0.17.1¶
Prelude¶
This is a bugfix release that fixes several issues from the 0.17.0 release. Most importantly this release fixes the incorrectly constructed sdist package for the 0.17.0 release which was not actually buildable and was blocking installation on platforms without precompiled binaries available.
Bug Fixes¶
-
Fixed an issue where the
global_phase
attribute would not be preserved in the outputQuantumCircuit
object when theqiskit.circuit.QuantumCircuit.reverse_bits()
method was called. For example:import math from qiskit import QuantumCircuit qc = QuantumCircuit ( 3 , 2 , global_phase = math . pi ) qc . h ( 0 ) qc . s ( 1 ) qc . cx ( 0 , 1 ) qc . measure ( 0 , 1 ) qc . x ( 0 ) qc . y ( 1 ) reversed = qc . reverse_bits () print ( reversed . global_phase )
will now correctly print \(\pi\).
-
Fixed an issue where the transpiler pass
Unroller
didn't preserve global phase in case of nested instructions with one rule in their definition. Fixed #6134 -
Fixed an issue where the
parameter
attribute of aControlledGate
object built from aUnitaryGate
was not being set to the unitary matrix of theUnitaryGate
object. Previously,control()
was building aControlledGate
with theparameter
attribute set to the controlled version ofUnitaryGate
matrix. This would lead to a modification of theparameter
of the baseUnitaryGate
object and subsequent calls toinverse()
was creating the inverse of a double-controlledUnitaryGate
. Fixed #5750 -
Fixed an issue with the preset pass managers
level_0_pass_manager
andlevel_1_pass_manager
(which corresponds tooptimization_level
0 and 1 fortranspile()
) where in some cases they would produce circuits not in the requested basis. -
Fix a bug where using
SPSA
with automatic calibration of the learning rate and perturbation (i.e.learning_rate
andperturbation
areNone
in the initializer), stores the calibration for all future optimizations. Instead, the calibration should be done for each new objective function.
Aer 0.8.1¶
Bug Fixes¶
-
Fixed an issue with use of the
matrix_product_state
method of theAerSimulator
andQasmSimulator
simulators when running a noisy simulation with Kraus errors. Previously, the matrix product state simulation method would not propogate changes to neighboring qubits after applying the Kraus matrix. This has been fixed so the output from the simulation is correct. Fixed #1184 and #1205 -
Fixed an issue where the
qiskit.extensions.Initialize
instruction would disable measurement sampling optimization for thestatevector
andmatrix_product_state
simulation methods of theAerSimulator
andQasmSimulator
simulators, even when it was the first circuit instruction or applied to all qubits and hence deterministic. Fixed #1210 -
Fix an issue with the
SaveStatevector
andSnapshotStatevector
instructions when used with theextended_stabilizer
simulation method of theAerSimulator
andQasmSimulator
simulators where it would return an unnormalized statevector. Fixed #1196 -
The
matrix_product_state
simulation method now has support for it's previously missing set state instruction,qiskit.providers.aer.library.SetMatrixProductState
, which enables setting the state of a simulation in a circuit.
Aqua 0.9.1¶
IBM Q Provider 0.12.2¶
No change
Qiskit 0.25.0¶
This release officially deprecates the Qiskit Aqua project. Accordingly, in a future release the qiskit-aqua
package will be removed from the Qiskit metapackage, which means in that future release pip install qiskit
will no longer include qiskit-aqua
. The application modules that are provided by qiskit-aqua have been split into several new packages: qiskit-optimization
, qiskit-nature
, qiskit-machine-learning
, and qiskit-finance
. These packages can be installed by themselves (via the standard pip install command, e.g. pip install qiskit-nature
) or with the rest of the Qiskit metapackage as optional extras (e.g. pip install 'qiskit[finance,optimization]'
or pip install 'qiskit[all]'
The core algorithms and the operator flow now exist as part of qiskit-terra at qiskit.algorithms
and qiskit.opflow
. Depending on your existing usage of Aqua you should either use the application packages or the new modules in Qiskit Terra. For more details on how to migrate from Qiskit Aqua you can refer to the aqua-migration.
Terra 0.17.0¶
Prelude¶
The Qiskit Terra 0.17.0 includes many new features and bug fixes. The major new feature for this release is the introduction of the qiskit.algorithms
and qiskit.opflow
modules which were migrated and adapted from the qiskit.aqua
project.
New Features¶
-
The
qiskit.pulse.call()
function can now take aParameter
object along with a parameterized subroutine. This enables assigning different values to theParameter
objects for each subroutine call.For example,
from qiskit.circuit import Parameter from qiskit import pulse amp = Parameter ( 'amp' ) with pulse . build () as subroutine : pulse . play ( pulse . Gaussian ( 160 , amp , 40 ), DriveChannel ( 0 )) with pulse . build () as main_prog : pulse . call ( subroutine , amp = 0.1 ) pulse . call ( subroutine , amp = 0.3 )
-
The
qiskit.providers.models.QasmBackendConfiguration
has a new fieldprocessor_type
which can optionally be used to provide information about a backend's processor in the form:{"family": <str>, "revision": <str>, segment: <str>}
. For example:{"family": "Canary", "revision": "1.0", segment: "A"}
. -
The
qiskit.pulse.Schedule
,qiskit.pulse.Instruction
, andqiskit.pulse.Channel
classes now have aparameter
property which will return anyParameter
objects used in the object and ais_parameterized()
method which will returnTrue
if any parameters are used in the object.For example:
from qiskit.circuit import Parameter from qiskit import pulse shift = Parameter ( 'alpha' ) schedule = pulse . Schedule () schedule += pulse . SetFrequency ( shift , pulse . DriveChannel ( 0 )) assert schedule . is_parameterized () == True print ( schedule . parameters )
-
Added a
PiecewiseChebyshev
to theqiskit.circuit.library
for implementing a piecewise Chebyshev approximation of an input function. For a given function \(f(x)\) and degree \(d\), this class class implements a piecewise polynomial Chebyshev approximation on \(n\) qubits to \(f(x)\) on the given intervals. All the polynomials in the approximation are of degree \(d\).For example:
import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev f_x , degree , breakpoints , num_state_qubits = lambda x : np . arcsin ( 1 / x ), 2 , [ 2 , 4 ], 2 pw_approximation = PiecewiseChebyshev ( f_x , degree , breakpoints , num_state_qubits ) pw_approximation . _build () qc = QuantumCircuit ( pw_approximation . num_qubits ) qc . h ( list ( range ( num_state_qubits ))) qc . append ( pw_approximation . to_instruction (), qc . qubits ) qc . draw ( output = 'mpl' )
-
The
BackendProperties
class now has areadout_length()
method, which returns the readout length [sec] of the given qubit. -
A new class,
ScheduleBlock
, has been added to theqiskit.pulse
module. This class provides a new representation of a pulse program. This representation is best suited for the pulse builder syntax and is based on relative instruction ordering.This representation takes
alignment_context
instead of specifying starting timet0
for each instruction. The start time of instruction is implicitly allocated with the specified transformation and relative position of instructions.The
ScheduleBlock
allows for lazy instruction scheduling, meaning we can assign arbitrary parameters to the duration of instructions.For example:
from qiskit.pulse import ScheduleBlock , DriveChannel , Gaussian from qiskit.pulse.instructions import Play , Call from qiskit.pulse.transforms import AlignRight from qiskit.circuit import Parameter dur = Parameter ( 'rabi_duration' ) block = ScheduleBlock ( alignment_context = AlignRight ()) block += Play ( Gaussian ( dur , 0.1 , dur / 4 ), DriveChannel ( 0 )) block += Call ( measure_sched ) # subroutine defined elsewhere
this code defines an experiment scanning a Gaussian pulse's duration followed by a measurement
measure_sched
, i.e. a Rabi experiment. You can reuse theblock
object for every scanned duration by assigning a target duration value. -
Added a new function
array_to_latex()
to theqiskit.visualization
module that can be used to represent and visualize vectors and matrices with LaTeX.from qiskit.visualization import array_to_latex from numpy import sqrt , exp , pi mat = [[ 0 , exp ( pi * .75 j )], [ 1 / sqrt ( 8 ), 0.875 ]] array_to_latex ( mat )
\[\begin{split}\begin{bmatrix} 0 & \tfrac{1}{\sqrt{2}}(-1 + i) \\ \tfrac{1}{\sqrt{8}} & \tfrac{7}{8} \\ \end{bmatrix} \end{split}\]
-
The
Statevector
andDensityMatrix
classes now havedraw()
methods which allow objects to be drawn as either text matrices, IPython Latex objects, Latex source, Q-spheres, Bloch spheres and Hinton plots. By default the output type is the equivalent output from__repr__
but this default can be changed in a user config file by setting thestate_drawer
option. For example:from qiskit.quantum_info import DensityMatrix dm = DensityMatrix . from_label ( 'r0' ) dm . draw ( 'latex' )
\[\begin{split}\begin{bmatrix} \tfrac{1}{2} & 0 & -\tfrac{1}{2}i & 0 \\ 0 & 0 & 0 & 0 \\ \tfrac{1}{2}i & 0 & \tfrac{1}{2} & 0 \\ 0 & 0 & 0 & 0 \\ \end{bmatrix} \end{split}\]
from qiskit.quantum_info import Statevector sv = Statevector . from_label ( '+r' ) sv . draw ( 'qsphere' )
Additionally, the
draw()
method is now used for the ipython display of these classes, so if you change the default output type in a user config file then when aStatevector
or aDensityMatrix
object are displayed in a jupyter notebook that output type will be used for the object. -
Pulse
qiskit.pulse.Instruction
objects and parametric pulse objects (egGaussian
now support usingParameter
andParameterExpression
objects for theduration
parameter. For example:from qiskit.circuit import Parameter from qiskit.pulse import Gaussian dur = Parameter ( 'x_pulse_duration' ) double_dur = dur * 2 rx_pulse = Gaussian ( dur , 0.1 , dur / 4 ) double_rx_pulse = Gaussian ( double_dir , 0.1 , dur / 4 )
Note that while we can create an instruction with a parameterized
duration
adding an instruction with unbound parameterduration
to a schedule is supported only by the newly introduced representationScheduleBlock
. See the known issues release notes section for more details. -
The
run()
method for theQasmSimulatorPy
,StatevectorSimulatorPy
, andUnitarySimulatorPy
backends now takes aQuantumCircuit
(or a list ofQuantumCircuit
objects) as its input. The previousQasmQobj
object is still supported for now, but will be deprecated in a future release.For an example of how to use this see:
from qiskit import transpile , QuantumCircuit from qiskit.providers.basicaer import BasicAer backend = BasicAer . get_backend ( 'qasm_simulator' ) circuit = QuantumCircuit ( 2 ) circuit . h ( 0 ) circuit . cx ( 0 , 1 ) circuit . measure_all () tqc = transpile ( circuit , backend ) result = backend . run ( tqc , shots = 4096 ) . result ()
-
The
CommutativeCancellation
transpiler pass has a new optional kwarg on the constructorbasis_gates
, which takes the a list of the names of basis gates for the target backend. When specified the pass will only use gates in thebasis_gates
kwarg. Previously, the pass would automatically replace consecutive gates which commute withZGate
with theU1Gate
unconditionally. Thebasis_gates
kwarg enables you to specify which z-rotation gates are present in the target basis to avoid this. -
The constructors of the
Bit
class and subclasses,Qubit
,Clbit
, andAncillaQubit
, have been updated such that their two parameters,register
andindex
are now optional. This enables the creation of bit objects that are independent of a register. -
A new class,
BooleanExpression
, has been added to theqiskit.circuit.classicalfunction
module. This class allows for creating an oracle from a Python boolean expression. For example:from qiskit.circuit import BooleanExpression , QuantumCircuit expression = BooleanExpression ( '~x & (y | z)' ) circuit = QuantumCircuit ( 4 ) circuit . append ( expression , [ 0 , 1 , 2 , 3 ]) circuit . draw ( 'mpl' )
circuit . decompose () . draw ( 'mpl' )
The
BooleanExpression
also includes a method,from_dimacs_file()
, which allows loading formulas described in the DIMACS-CNF format. For example:from qiskit.circuit import BooleanExpression , QuantumCircuit boolean_exp = BooleanExpression . from_dimacs_file ( "simple_v3_c2.cnf" ) circuit = QuantumCircuit ( boolean_exp . num_qubits ) circuit . append ( boolean_exp , range ( boolean_exp . num_qubits )) circuit . draw ( 'text' )
┌───────────────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 ├ │ SIMPLE_V3_C2.CNF │ q_2: ┤2 ├ │ │ q_3: ┤3 ├ └───────────────────┘
circuit . decompose () . draw ( 'text' )
q_0: ──o────o──────────── │ │ q_1: ──■────o────■─────── │ │ │ q_2: ──■────┼────o────■── ┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐ q_3: ┤ X ├┤ X ├┤ X ├┤ X ├ └───┘└───┘└───┘└───┘
-
Added a new class,
PhaseOracle
, has been added to theqiskit.circuit.library
module. This class enables the construction of phase oracle circuits from Python boolean expressions.from qiskit.circuit.library.phase_oracle import PhaseOracle oracle = PhaseOracle ( 'x1 & x2 & (not x3)' ) oracle . draw ( 'mpl' )
These phase oracles can be used as part of a larger algorithm, for example with
qiskit.algorithms.AmplificationProblem
:from qiskit.algorithms import AmplificationProblem , Grover from qiskit import BasicAer backend = BasicAer . get_backend ( 'qasm_simulator' ) problem = AmplificationProblem ( oracle , is_good_state = oracle . evaluate_bitstring ) grover = Grover ( quantum_instance = backend ) result = grover . amplify ( problem ) result . top_measurement
The
PhaseOracle
class also includes afrom_dimacs_file()
method which enables constructing a phase oracle from a file describing a formula in the DIMACS-CNF format.from qiskit.circuit.library.phase_oracle import PhaseOracle oracle = PhaseOracle . from_dimacs_file ( "simple_v3_c2.cnf" ) oracle . draw ( 'text' )
state_0: ─o───────o────────────── │ ┌───┐ │ ┌───┐ state_1: ─■─┤ X ├─■─┤ X ├─■────── │ └───┘ └───┘ │ ┌───┐ state_2: ─■───────────────o─┤ Z ├ └───┘
-
All transpiler passes (ie any instances of
BasePass
) are now directly callable. Calling a pass provides a convenient interface for running the pass on aQuantumCircuit
object.For example, running a single transformation pass, such as
BasisTranslator
, can be done with:from qiskit import QuantumCircuit from qiskit.transpiler.passes import BasisTranslator from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel circuit = QuantumCircuit ( 1 ) circuit . h ( 0 ) pass_instance = BasisTranslator ( sel , [ 'rx' , 'rz' , 'cx' ]) result = pass_instance ( circuit ) result . draw ( output = 'mpl' )
When running an analysis pass, a property set (as
dict
or asPropertySet
) needs to be added as a parameter and it might be modified "in-place". For example:from qiskit import QuantumCircuit from qiskit.transpiler.passes import Depth circuit = QuantumCircuit ( 1 ) circuit . h ( 0 ) property_set = {} pass_instance = Depth () pass_instance ( circuit , property_set ) print ( property_set )
-
The
QasmQobjConfig
class now has an optional kwarg formeas_level
andmeas_return
. These fields can be used to enable generatingQasmQobj
job payloads that supportmeas_level=1
(kerneled data) for circuit jobs (previously this was only exposed forPulseQobj
objects). Theassemble()
function has been updated to set this field forQasmQobj
objects it generates. -
A new
tensor()
method has been added to theQuantumCircuit
class. This method enables tensoring another circuit with an existing circuit. This method works analogously toqiskit.quantum_info.Operator.tensor()
and is consistent with the little-endian convention of Qiskit.For example:
from qiskit import QuantumCircuit top = QuantumCircuit ( 1 ) top . x ( 0 ); bottom = QuantumCircuit ( 2 ) bottom . cry ( 0.2 , 0 , 1 ); bottom . tensor ( top ) . draw ( output = 'mpl' )
-
The
qiskit.circuit.QuantumCircuit
class now supports arbitrary free form metadata with themetadata
attribute. A user (or program built on top ofQuantumCircuit
) can attach metadata to a circuit for use in tracking the circuit. For example:from qiskit.circuit import QuantumCircuit qc = QuantumCircuit ( 2 , user_metadata_field_1 = 'my_metadata' , user_metadata_field_2 = 'my_other_value' )
or:
from qiskit.circuit import QuantumCircuit qc = QuantumCircuit ( 2 ) qc . metadata = { 'user_metadata_field_1' : 'my_metadata' , 'user_metadata_field_2' : 'my_other_value' }
This metadata will not be used for influencing the execution of the circuit but is just used for tracking the circuit for the lifetime of the object. The
metadata
attribute will persist between any circuit transforms includingtranspile()
andassemble()
. The expectation is for providers to associate the metadata in the result it returns, so that users can filter results based on circuit metadata the same way they can currently do withQuantumCircuit.name
. -
Add a new operator class
CNOTDihedral
has been added to theqiskit.quantum_info
module. This class is used to represent the CNOT-Dihedral group, which is generated by the quantum gatesCXGate
,TGate
, andXGate
. -
Adds a
&
(__and__
) binary operator toBaseOperator
subclasses (egqiskit.quantum_info.Operator
) in theqiskit.quantum_info
module. This is shorthand to call the classescompose()
method (ieA & B == A.compose(B)
).For example:
import qiskit.quantum_info as qi qi . Pauli ( 'X' ) & qi . Pauli ( 'Y' )
-
Adds a
&
(__and__
) binary operator toqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes. This is shorthand to call the classesevolve()
method (iepsi & U == psi.evolve(U)
).For example:
import qiskit.quantum_info as qi qi . Statevector . from_label ( '0' ) & qi . Pauli ( 'X' )
-
A new a new 2-qubit gate,
ECRGate
, the echo cross-resonance (ECR), has been added to theqiskit.circuit.library
module along with a corresponding method,ecr()
for theQuantumCircuit
class. The ECR gate is two \(CR(\frac{π}{4})\) pulses with anXGate
between them for the echo. This gate is locally equivalent to aCXGate
(can convert to a CNOT with local pre- or post-rotation). It is the native gate on current IBM hardware and compiling to it allows the pre-/post-rotations to be merged into the rest of the circuit. -
A new kwarg
approximation_degree
has been added to thetranspile()
function for enabling approximate compilation. Valid values range from 0 to 1, and higher means less approximation. This is a heuristic dial to experiment with circuit approximations. The concrete interpretation of this number is left to each pass, which may use it to perform some approximate version of the pass. Specific examples include theUnitarySynthesis
pass or the or translators to discrete gate sets. If a pass does not support this option, it implies exact transformation. -
Two new transpiler passess,
GateDirection
andqiskit.transpiler.passes.CheckGateDirection
, were added to theqiskit.transpiler.passes
module. These new passes are inteded to be more general replacements forCXDirection
andCheckCXDirection
(which are both now deprecated, see the deprecation notes for more details) that perform the same function but work with other gates beside justCXGate
. -
When running on Windows, parallel execution with the
parallel_map()
function can now be enabled (it is still disabled by default). To do this you can either setparallel = True
in a user config file, or set theQISKIT_PARALLEL
environment variable toTRUE
(this will also effecttranspile()
andassemble()
which both useparallel_map()
internally). It is important to note that when enabling parallelism on Windows there are limitations around how Python launches processes for Windows, see the Known Issues section below for more details on the limitations with parallel execution on Windows. -
A new function,
hellinger_distance()
, for computing the Hellinger distance between two counts distributions has been added to theqiskit.quantum_info
module. -
The
decompose_clifford()
function in theqiskit.quantum_info
module (which gets used internally by theqiskit.quantum_info.Clifford.to_circuit()
method) has a new kwargmethod
which enables selecting the synthesis method used by either setting it to'AG'
or'greedy'
. By default for more than three qubits it is set to'greedy'
which uses a non-optimal greedy compilation routine for Clifford elements synthesis, by Bravyi et. al., which typically yields better CX cost compared to the previously used Aaronson-Gottesman method (for more than two qubits). You can use themethod
kwarg to revert to the previous default Aaronson-Gottesman method by settingmethod='AG'
. -
The
Initialize
class in theqiskit.extensions
module can now be constructed using an integer. The '1' bits of the integer will insert aReset
and anXGate
into the circuit for the corresponding qubit. This will be done using the standard little-endian convention is qiskit, ie the rightmost bit of the integer will set qubit 0. For example, setting the parameter inInitialize
equal to5
will set qubits 0 and 2 to value 1.from qiskit.extensions import Initialize initialize = Initialize ( 13 ) initialize . definition . draw ( 'mpl' )
-
The
Initialize
class in theqiskit.extensions
module now supports constructing directly from a Pauli label (analogous to theqiskit.quantum_info.Statevector.from_label()
method). The Pauli label refer to basis states of the Pauli eigenstates Z, X, Y. These labels use Qiskit's standard little-endian notation, for example a label of'01'
would initialize qubit 0 to \(|1\rangle\) and qubit 1 to \(|0\rangle\).from qiskit.extensions import Initialize initialize = Initialize ( "10+-lr" ) initialize . definition . draw ( 'mpl' )
-
The kwarg,
template_list
, for the constructor of theqiskit.transpiler.passes.TemplateOptimization
transpiler pass now supports taking in a list of bothQuantumCircuit
andDAGDependency
objects. Previously, onlyQuantumCircuit
were accepted (which were internally converted toDAGDependency
objects) in the input list. -
A new transpiler pass,
qiskit.transpiler.passes.RZXCalibrationBuilder
, capable of generating calibrations and adding them to a quantum circuit has been introduced. This pass takes calibratedCXGate
objects and creates the calibrations forqiskit.circuit.library.RZXGate
objects with an arbitrary rotation angle. The schedules are created by stretching and compressing theGaussianSquare
pulses of the echoed-cross resonance gates. -
New template circuits for using
qiskit.circuit.library.RZXGate
are added to theqiskit.circuit.library
module (egrzx_yz
). This enables pairing theTemplateOptimization
pass with theqiskit.transpiler.passes.RZXCalibrationBuilder
pass to automatically find and replace gate sequences, such asCNOT - P(theta) - CNOT
, with more efficent circuits based onqiskit.circuit.library.RZXGate
with a calibration. -
The matplotlib output type for the
circuit_drawer()
and thedraw()
method for theQuantumCircuit
class now supports configuration files for setting the visualization style. In previous releases, there was basic functionality that allowed users to pass in astyle
kwarg that took in adict
to customize the colors and other display features of thempl
drawer. This has now been expanded so that these dictionaries can be loaded from JSON files directly without needing to pass a dictionary. This enables users to create new style files and use that style for visualizations by passing the style filename as a string to thestyle
kwarg.To leverage this feature you must set the
circuit_mpl_style_path
option in a user config file. This option should be set to the path you want qiskit to search for style JSON files. If specifying multiple path entries they should be separated by:
. For example, settingcircuit_mpl_style_path = ~/.qiskit:~/user_styles
in a user config file will look for JSON files in both~/.qiskit
and~/user_styles
. -
A new kwarg,
format_marginal
has been added to the functionmarginal_counts()
which when set toTrue
formats the counts output according to thecregs
in the circuit and missing indices are represented with a_
. For example:from qiskit import QuantumCircuit , execute , BasicAer , result from qiskit.result.utils import marginal_counts qc = QuantumCircuit ( 5 , 5 ) qc . x ( 0 ) qc . measure ( 0 , 0 ) result = execute ( qc , BasicAer . get_backend ( 'qasm_simulator' )) . result () print ( marginal_counts ( result . get_counts (), [ 0 , 2 , 4 ], format_marginal = True ))
-
Improved the performance of
qiskit.quantum_info.Statevector.expectation_value()
andqiskit.quantum_info.DensityMatrix.expectation_value()
when the argument operator is aPauli
orSparsePauliOp
operator. -
The user config file has 2 new configuration options,
num_processes
andparallel
, which are used to control the default behavior ofparallel_map()
. Theparallel
option is a boolean that is used to dictate whetherparallel_map()
will run in multiple processes or not. If it set toFalse
calls toparallel_map()
will be executed serially, while setting it toTrue
will enable parallel execution. Thenum_processes
option takes an integer which sets how many CPUs to use when executing in parallel. By default it will use the number of CPU cores on a system. -
There are 2 new environment variables,
QISKIT_PARALLEL
andQISKIT_NUM_PROCS
, that can be used to control the default behavior ofparallel_map()
. TheQISKIT_PARALLEL
option can be set to theTRUE
(any capitalization) to set the default to run in multiple processes whenparallel_map()
is called. If it is set to any other valueparallel_map()
will be executed serially.QISKIT_NUM_PROCS
takes an integer (for exampleQISKIT_NUM_PROCS=5
) which will be used as the default number of processes to run with. Both of these will take precedence over the equivalent option set in the user config file. -
A new method,
gradient()
, has been added to theParameterExpression
class. This method is used to evaluate the gradient of aParameterExpression
object. -
The
__eq__
method (ie what is called when the==
operator is used) for theParameterExpression
now allows for the comparison with a numeric value. Previously, it was only possible to compare two instances ofParameterExpression
with==
. For example:from qiskit.circuit import Parameter x = Parameter ( "x" ) y = x + 2 y = y . assign ( x , - 1 ) assert y == 1
-
The
PauliFeatureMap
class in theqiskit.circuit.library
module now supports adjusting the rotational factor, \(\alpha\), by either setting using the kwargalpha
on the constructor or setting thealpha
attribute after creation. Previously this value was fixed at2.0
. Adjusting this attribute allows for better control of decision boundaries and provides additional flexibility handling the input features without needing to explicitly scale them in the data set. -
A new
Gate
class,PauliGate
, has been added theqiskit.circuit.library
module and corresponding method,pauli()
, was added to theQuantumCircuit
class. This new gate class enables applying several individual pauli gates to different qubits at the simultaneously. This is primarily useful for simulators which can use this new gate to more efficiently implement multiple simultaneous Pauli gates. -
Improve the
qiskit.quantum_info.Pauli
operator. This class now represents and element from the full N-qubit Pauli group including complex coefficients. It now supports the Operator API methods includingcompose()
,dot()
,tensor()
etc, where compose and dot are defined with respect to the full Pauli group.This class also allows conversion to and from the string representation of Pauli's for convenience.
For example
from qiskit.quantum_info import Pauli P1 = Pauli ( 'XYZ' ) P2 = Pauli ( 'YZX' ) P1 . dot ( P2 )
Pauli's can also be directly appended to
QuantumCircuit
objectsfrom qiskit import QuantumCircuit from qiskit.quantum_info import Pauli circ = QuantumCircuit ( 3 ) circ . append ( Pauli ( 'XYZ' ), [ 0 , 1 , 2 ]) circ . draw ( output = 'mpl' )
Additional methods allow computing when two Pauli's commute (using the
commutes()
method) or anticommute (using theanticommutes()
method), and computing the Pauli resulting from Clifford conjugation \(P^\prime = C.P.C^\dagger\) using theevolve()
method.See the API documentation of the
Pauli
class for additional information. -
A new function,
random_pauli()
, for generating a random element of the N-qubit Pauli group has been added to theqiskit.quantum_info
module. -
A new class,
PiecewisePolynomialPauliRotations
, has been added to theqiskit.circuit.library
module. This circuit library element is used for mapping a piecewise polynomial function, \(f(x)\), which is defined through breakpoints and coefficients, on qubit amplitudes. The breakpoints \((x_0, ..., x_J)\) are a subset of \([0, 2^n-1]\), where \(n\) is the number of state qubits. The corresponding coefficients \([a_{j,1},...,a_{j,d}]\), where \(d\) is the highest degree among all polynomials. Then \(f(x)\) is defined as:\[\begin{split}f(x) = \begin{cases} 0, x < x_0 \\ \sum_{i=0}^{i=d}a_{j,i} x^i, x_j \leq x < x_{j+1} \end{cases}\end{split}\]
where we implicitly assume \(x_{J+1} = 2^n\). And the mapping applied to the amplitudes is given by
\[F|x\rangle |0\rangle = \cos(p_j(x))|x\rangle |0\rangle + \sin(p_j(x))|x\rangle |1\rangle\]
This mapping is based on controlled Pauli Y-rotations and constructed using the
PolynomialPauliRotations
. -
A new module
qiskit.algorithms
has been introduced. This module contains functionality equivalent to what has previously been provided by theqiskit.aqua.algorithms
module (which is now deprecated) and provides the building blocks for constructing quantum algorithms. For details on migrating fromqiskit-aqua
to this new module please refer to the migration guide aqua-migration -
A new module
qiskit.opflow
has been introduced. This module contains functionality equivalent to what has previously been provided by theqiskit.aqua.operators
module (which is now deprecated) and provides the operators and state functions which are used to build quantum algorithms. For details on migrating fromqiskit-aqua
to this new module please refer to the migration guide aqua-migration -
This is the first release that includes precompiled binary wheels for the for Linux aarch64 systems. If you are running a manylinux2014 compatible aarch64 Linux system there are now precompiled wheels available on PyPI, you are no longer required to build from source to install qiskit-terra.
-
The
qiskit.quantum_info.process_fidelity()
function is now able to be used with a non-unitary target channel. In this case the returned value is equivalent to theqiskit.quantum_info.state_fidelity()
of the normalizedqiskit.quantum_info.Choi
matrices for the channels.Note that the
qiskit.quantum_info.average_gate_fidelity()
andqiskit.quantum_info.gate_error()
functions still require the target channel to be unitary and will raise an exception if it is not. -
Added a new pulse builder function,
qiskit.pulse.macro()
. This enables normal Python functions to be decorated as macros. This enables pulse builder functions to be used within the decorated function. The builder macro can then be called from within a pulse building context, enabling code reuse.For Example:
from qiskit import pulse @pulse . macro def measure ( qubit : int ): pulse . play ( pulse . GaussianSquare ( 16384 , 256 , 15872 ), pulse . MeasureChannel ( qubit )) mem_slot = pulse . MemorySlot ( 0 ) pulse . acquire ( 16384 , pulse . AcquireChannel ( 0 ), mem_slot ) return mem_slot with pulse . build ( backend = backend ) as sched : mem_slot = measure ( 0 ) print ( f "Qubit measured into { mem_slot } " ) sched . draw ()
-
A new class,
PauliTwoDesign
, was added to theqiskit.circuit.library
which implements a particular form of a 2-design circuit from https://arxiv.org/pdf/1803.11173.pdf For instance, this circuit can look like:from qiskit.circuit.library import PauliTwoDesign circuit = PauliTwoDesign ( 4 , reps = 2 , seed = 5 , insert_barriers = True ) circuit . decompose () . draw ( output = 'mpl' )
-
A new pulse drawer
qiskit.visualization.pulse_v2.draw()
(which is aliased asqiskit.visualization.pulse_drawer_v2
) is now available. This new pulse drawer supports multiple new features not present in the original pulse drawer (pulse_drawer()
).-
Truncation of long pulse instructions.
-
Visualization of parametric pulses.
-
New stylesheets
IQXStandard
,IQXSimple
,IQXDebugging
. -
Visualization of system info (channel frequency, etc…) by specifying
qiskit.providers.Backend
objects for visualization. -
Specifying
axis
objects for plotting to allow further extension of generated plots, i.e., for publication manipulations.
New stylesheets can take callback functions that dynamically modify the apperance of the output image, for example, reassembling a collection of channels, showing details of instructions, updating appearance of pulse envelopes, etc… You can create custom callback functions and feed them into a stylesheet instance to modify the figure appearance without modifying the drawer code. See pulse drawer module docstrings for details.
Note that file saving is now delegated to Matplotlib. To save image files, you need to call
savefig
method with returnedFigure
object. -
-
Adds a
reverse_qargs()
method to theqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes. This method reverses the order of subsystems in the states and is equivalent to theqiskit.circuit.QuantumCircuit.reverse_bits()
method for N-qubit states. For example:from qiskit.circuit.library import QFT from qiskit.quantum_info import Statevector circ = QFT ( 3 ) state1 = Statevector . from_instruction ( circ ) state2 = Statevector . from_instruction ( circ . reverse_bits ()) state1 . reverse_qargs () == state2
-
Adds a
reverse_qargs()
method to theqiskit.quantum_info.Operator
class. This method reverses the order of subsystems in the operator and is equivalent to theqiskit.circuit.QuantumCircuit.reverse_bits()
method for N-qubit operators. For example:from qiskit.circuit.library import QFT from qiskit.quantum_info import Operator circ = QFT ( 3 ) op1 = Operator ( circ ) op2 = Operator ( circ . reverse_bits ()) op1 . reverse_qargs () == op2
-
The
latex
output method for theqiskit.visualization.circuit_drawer()
function and thedraw()
method now will use a user defined label on gates in the output visualization. For example:import math from qiskit.circuit import QuantumCircuit qc = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . rx ( math . pi / 2 , 0 , label = 'My Special Rotation' ) qc . draw ( output = 'latex' )
-
The
routing_method
kwarg for thetranspile()
function now accepts a new option,'none'
. Whenrouting_method='none'
no routing pass will be run as part of the transpilation. If the circuit does not fit coupling map aTranspilerError
exception will be raised. -
A new gate class,
RVGate
, was added to theqiskit.circuit.library
module along with the correspondingQuantumCircuit
methodrv()
. TheRVGate
is a general rotation gate, similar to theUGate
, but instead of specifying Euler angles the three components of a rotation vector are specified where the direction of the vector specifies the rotation axis and the magnitude specifies the rotation angle about the axis in radians. For example:import math import np from qiskit.circuit import QuantumCircuit qc = QuantumCircuit ( 1 ) theta = math . pi / 5 phi = math . pi / 3 # RGate axis: axis = np . array ([ math . cos ( phi ), math . sin ( phi )]) rotation_vector = theta * axis qc . rv ( * rotation_vector , 0 )
-
Unbound
Parameter
objects used in aQuantumCircuit
object will now be sorted by name. This will take effect for the parameters returned by theparameters
attribute. Additionally, theqiskit.circuit.QuantumCircuit.bind_parameters()
andqiskit.circuit.QuantumCircuit.assign_parameters()
methods can now take in a list of a values which will bind/assign them to the parameters in name-sorted order. Previously these methods would only take a dictionary of parameters and values. For example:from qiskit.circuit import QuantumCircuit , Parameter circuit = QuantumCircuit ( 1 ) circuit . rx ( Parameter ( 'x' ), 0 ) circuit . ry ( Parameter ( 'y' ), 0 ) print ( circuit . parameters ) bound = circuit . bind_parameters ([ 1 , 2 ]) bound . draw ( output = 'mpl' )
ParameterView([Parameter(x), Parameter(y)])
-
The constructors for the
qiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes can now take aQuantumCircuit
object in to build aStatevector
andDensityMatrix
object from that circuit, assuming that the qubits are initialized in \(|0\rangle\). For example:from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector qc = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) statevector = Statevector ( qc ) statevector . draw ( output = 'latex' )
\[\frac{\sqrt{2}}{2} |00\rangle+\frac{\sqrt{2}}{2} |11\rangle\]
-
New fake backend classes are available under
qiskit.test.mock
. These included mocked versions ofibmq_casablanca
,ibmq_sydney
,ibmq_mumbai
,ibmq_lima
,ibmq_belem
,ibmq_quito
. As with the other fake backends, these include snapshots of calibration data (i.e.backend.defaults()
) and error data (i.e.backend.properties()
) taken from the real system, and can be used for local testing, compilation and simulation.
Known Issues¶
-
Attempting to add an
qiskit.pulse.Instruction
object with a parameterizedduration
(ie the value ofduration
is an unboundParameter
orParameterExpression
object) to aqiskit.pulse.Schedule
is not supported. Attempting to do so will result inUnassignedDurationError
PulseError
being raised. This is a limitation of how theInstruction
overlap constraints are evaluated currently. This is supported byScheduleBlock
, in which the overlap constraints are evaluated just before the execution. -
On Windows systems when parallel execution is enabled for
parallel_map()
parallelism may not work when called from a script running outside of aif __name__ == '__main__':
block. This is due to how Python launches parallel processes on Windows. If aRuntimeError
orAttributeError
are raised by scripts that callparallel_map()
(including using functions that useparallel_map()
internally liketranspile()
) with Windows and parallelism enabled you can try embedding the script calls insideif __name__ == '__main__':
to workaround the issue. For example:from qiskit import QuantumCircuit , QiskitError from qiskit import execute , Aer qc1 = QuantumCircuit ( 2 , 2 ) qc1 . h ( 0 ) qc1 . cx ( 0 , 1 ) qc1 . measure ([ 0 , 1 ], [ 0 , 1 ]) # making another circuit: superpositions qc2 = QuantumCircuit ( 2 , 2 ) qc2 . h ([ 0 , 1 ]) qc2 . measure ([ 0 , 1 ], [ 0 , 1 ]) execute ([ qc1 , qc2 ], Aer . get_backend ( 'qasm_simulator' ))
should be changed to:
from qiskit import QuantumCircuit , QiskitError from qiskit import execute , Aer def main (): qc1 = QuantumCircuit ( 2 , 2 ) qc1 . h ( 0 ) qc1 . cx ( 0 , 1 ) qc1 . measure ([ 0 , 1 ], [ 0 , 1 ]) # making another circuit: superpositions qc2 = QuantumCircuit ( 2 , 2 ) qc2 . h ([ 0 , 1 ]) qc2 . measure ([ 0 , 1 ], [ 0 , 1 ]) execute ([ qc1 , qc2 ], Aer . get_backend ( 'qasm_simulator' )) if __name__ == '__main__' : main ()
if any errors are encountered with parallelism on Windows.
Upgrade Notes¶
-
The preset pass managers
level_1_pass_manager
,level_2_pass_manager
, andlevel_3_pass_manager
(which are used foroptimization_level
1, 2, and 3 in thetranspile()
andexecute()
functions) now unconditionally use theOptimize1qGatesDecomposition
pass for 1 qubit gate optimization. Previously, these pass managers would use theOptimize1qGates
pass if the basis gates containedu1
,u2
, oru3
. If you want to still use the oldOptimize1qGates
you will need to construct a customPassManager
with the pass. -
Following transpilation of a parameterized
QuantumCircuit
, theglobal_phase
attribute of output circuit may no longer be returned in a simplified form, if the global phase is aParameterExpression
.For example:
qc = QuantumCircuit ( 1 ) theta = Parameter ( 'theta' ) qc . rz ( theta , 0 ) qc . rz ( - theta , 0 ) print ( transpile ( qc , basis_gates = [ 'p' ]) . global_phase )
previously returned
0
, but will now return-0.5*theta + 0.5*theta
. This change was necessary was to avoid a large runtime performance penalty as simplifying symbolic expressions can be quite slow, especially if there are manyParameterExpression
objects in a circuit. -
The
BasicAerJob
job objects returned from BasicAer backends are now synchronous instances ofJobV1
. This means that calls to therun()
will block until the simulation finishes executing. If you want to restore the previous async behavior you'll need to wrap therun()
with something that will run in a seperate thread or process likefutures.ThreadPoolExecutor
orfutures.ProcessPoolExecutor
. -
The
allow_sample_measuring
option for the BasicAer simulatorQasmSimulatorPy
has changed from a default ofFalse
toTrue
. This was done to better reflect the actual default behavior of the simulator, which would use sample measuring if the input circuit supported it (even if it was not enabled). If you are running a circuit that doesn't support sample measurement (ie it hasReset
operations or if there are operations after a measurement on a qubit) you should make sure to explicitly set this option toFalse
when you callrun()
. -
The
CommutativeCancellation
transpiler pass is now aware of the target basis gates, which means it will only use gates in the specified basis. Previously, the pass would unconditionally replace consecutive gates which commute withZGate
with theU1Gate
. However, now that the pass is basis aware and has a kwarg,basis_gates
, for specifying the target basis there is a potential change in behavior if the kwarg is not set. When thebasis_gates
kwarg is not used and there are no variable z-rotation gates in the circuit then no commutative cancellation will occur. -
Register
(which is the parent class forQuantumRegister
andClassicalRegister
andBit
(which is the parent class forQubit
andClbit
) objects are now immutable. In previous releases it was possible to adjust the value of asize
orname
attributes of aRegister
object and theindex
orregister
attributes of aBit
object after it was initially created. However this would lead to unsound behavior that would corrupt container structure that rely on a hash (such as a dict) since these attributes are treated as immutable properties of a register or bit (see #4705 for more details). To avoid this unsound behavior this attributes of aRegister
andBit
are no longer settable after initial creation. If you were previously adjusting the objects at runtime you will now need to create a newRegister
orBit
object with the new values. -
The
DAGCircuit.__eq__
method (which is used by the==
operator), which is used to check structural equality ofDAGCircuit
andQuantumCircuit
instances, will now include theglobal_phase
andcalibrations
attributes in the fields checked for equality. This means that circuits which would have evaluated as equal in prior releases may not anymore if theglobal_phase
orcalibrations
differ between the circuits. For example, in previous releases this would returnTrue
:import math from qiskit import QuantumCircuit qc1 = QuantumCircuit ( 1 ) qc1 . x ( 0 ) qc2 = QuantumCircuit ( 1 , global_phase = math . pi ) qc2 . x ( 0 ) print ( qc2 == qc1 )
However, now because the
global_phase
attribute of the circuits differ this will now returnFalse
. -
The previously deprecated
qubits()
andclbits()
methods on theDAGCircuit
class, which were deprecated in the 0.15.0 Terra release, have been removed. Instead you should use thequbits
andclbits
attributes of theDAGCircuit
class. For example, if you were running:from qiskit.dagcircuit import DAGCircuit dag = DAGCircuit () qubits = dag . qubits ()
That would be replaced by:
from qiskit.dagcircuit import DAGCircuit dag = DAGCircuit () qubits = dag . qubits
-
The
PulseDefaults
returned by the fake pulse backendsqiskit.test.mock.FakeOpenPulse2Q
andqiskit.test.mock.FakeOpenPulse3Q
have been updated to have more realistic pulse sequence definitions. If you are using these fake backend classes you may need to update your usage because of these changes. -
The default synthesis method used by
decompose_clifford()
function in thequantum_info
module (which gets used internally by theqiskit.quantum_info.Clifford.to_circuit()
method) for more than 3 qubits now uses a non-optimal greedy compilation routine for Clifford elements synthesis, by Bravyi et. al., which typically yields better CX cost compared to the old default. If you need to revert to the previous Aaronson-Gottesman method this can be done by settingmethod='AG'
. -
The previously deprecated module
qiskit.visualization.interactive
, which was deprecated in the 0.15.0 release, has now been removed. Instead you should use the matplotlib based visualizations:Removed Interactive function
Equivalent matplotlib function
iplot_bloch_multivector
qiskit.visualization.plot_bloch_multivector()
iplot_state_city
qiskit.visualization.plot_state_city()
iplot_state_qsphere
qiskit.visualization.plot_state_qsphere()
iplot_state_hinton
qiskit.visualization.plot_state_hinton()
iplot_histogram
qiskit.visualization.plot_histogram()
iplot_state_paulivec
qiskit.visualization.plot_state_paulivec()
-
The
qiskit.Aer
andqiskit.IBMQ
top level attributes are now lazy loaded. This means that the objects will now always exist and warnings will no longer be raised on import ifqiskit-aer
orqiskit-ibmq-provider
are not installed (or can't be found by Python). If you were checking for the presence ofqiskit-aer
orqiskit-ibmq-provider
using these module attributes and explicitly comparing toNone
or looking for the absence of the attribute this no longer will work because they are always defined as an object now. In other words running something like:try : from qiskit import Aer except ImportError : print ( "Aer not available" ) or :: try : from qiskit import IBMQ except ImportError : print ( "IBMQ not available" )
will no longer work. Instead to determine if those providers are present you can either explicitly use
qiskit.providers.aer.Aer
andqiskit.providers.ibmq.IBMQ
:try : from qiskit.providers.aer import Aer except ImportError : print ( "Aer not available" ) try : from qiskit.providers.ibmq import IBMQ except ImportError : print ( "IBMQ not available" )
or check
bool(qiskit.Aer)
andbool(qiskit.IBMQ)
instead, for example:import qiskit if not qiskit . Aer : print ( "Aer not available" ) if not qiskit . IBMQ : print ( "IBMQ not available" )
This change was necessary to avoid potential import cycle issues between the qiskit packages and also to improve the import time when Aer or IBMQ are not being used.
-
The user config file option
suppress_packaging_warnings
option in the user config file and theQISKIT_SUPPRESS_PACKAGING_WARNINGS
environment variable no longer has any effect and will be silently ignored. The warnings this option controlled have been removed and will no longer be emitted at import time from theqiskit
module. -
The previously deprecated
condition
kwarg forqiskit.dagcircuit.DAGNode
constructor has been removed. It was deprecated in the 0.15.0 release. Instead you should now be setting the classical condition on theInstruction
object passed into theDAGNode
constructor when creating a newop
node. -
When creating a new
Register
(which is the parent class forQuantumRegister
andClassicalRegister
) orQuantumCircuit
object with a number of bits (egQuantumCircuit(2)
), it is now required that number of bits are specified as an integer or another type which is castable to unambiguous integers(e.g.2.0
). Non-integer values will now raise an error as the intent in those cases was unclear (you can't have fractional bits). For more information on why this was changed refer to: #4855 -
networkx is no longer a requirement for qiskit-terra. All the networkx usage inside qiskit-terra has been removed with the exception of 3 methods:
-
qiskit.dagcircuit.DAGCircuit.to_networkx
-
qiskit.dagcircuit.DAGCircuit.from_networkx
-
qiskit.dagcircuit.DAGDependency.to_networkx
If you are using any of these methods you will need to manually install networkx in your environment to continue using them.
-
-
By default on macOS with Python >=3.8
parallel_map()
will no longer run in multiple processes. This is a change from previous releases where the default behavior was thatparallel_map()
would launch multiple processes. This change was made because with newer versions of macOS with Python 3.8 and 3.9 multiprocessing is either unreliable or adds significant overhead because of the change in Python 3.8 to launch new processes withspawn
instead offork
. To re-enable parallel execution on macOS with Python >= 3.8 you can use the user config fileparallel
option or set the environment variableQISKIT_PARALLEL
toTrue
. -
The previously deprecated kwarg
callback
on the constructor for thePassManager
class has been removed. This kwarg has been deprecated since the 0.13.0 release (April, 9th 2020). Instead you can pass thecallback
kwarg to theqiskit.transpiler.PassManager.run()
method directly. For example, if you were using:from qiskit.circuit.random import random_circuit from qiskit.transpiler import PassManager qc = random_circuit ( 2 , 2 ) def callback ( ** kwargs ) print ( kwargs [ 'pass_' ]) pm = PassManager ( callback = callback ) pm . run ( qc )
this can be replaced with:
from qiskit.circuit.random import random_circuit from qiskit.transpiler import PassManager qc = random_circuit ( 2 , 2 ) def callback ( ** kwargs ) print ( kwargs [ 'pass_' ]) pm = PassManager () pm . run ( qc , callback = callback )
-
It is now no longer possible to instantiate a base channel without a prefix, such as
qiskit.pulse.Channel
orqiskit.pulse.PulseChannel
. These classes are designed to classify types of different user facing channel classes, such asqiskit.pulse.DriveChannel
, but do not have a definition as a target resource. If you were previously directly instantiating eitherqiskit.pulse.Channel
orqiskit.pulse.PulseChannel
, this is no longer allowed. Please use the appropriate subclass. -
When the
require_cp
and/orrequire_tp
kwargs ofqiskit.quantum_info.process_fidelity()
,qiskit.quantum_info.average_gate_fidelity()
,qiskit.quantum_info.gate_error()
areTrue
, they will now only log a warning rather than the previous behavior of raising aQiskitError
exception if the input channel is non-CP or non-TP respectively. -
The
QFT
class in theqiskit.circuit.library
module now computes the Fourier transform using a little-endian representation of tensors, i.e. the state \(|1\rangle\) maps to \(|0\rangle - |1\rangle + |2\rangle - ..\) assuming the computational basis correspond to little-endian bit ordering of the integers. \(|0\rangle = |000\rangle, |1\rangle = |001\rangle\), etc. This was done to make it more consistent with the rest of Qiskit, which uses a little-endian convention for bit order. If you were depending on the previous bit order you can use thereverse_bits()
method to revert to the previous behavior. For example:from qiskit.circuit.library import QFT qft = QFT ( 5 ) . reverse_bits ()
-
The
qiskit.__qiskit_version__
module attribute was previously adict
will now return a custom read-onlyMapping
object that checks the version of qiskit elements at runtime instead of at import time. This was done to speed up the import path of qiskit and eliminate a possible import cycle by only importing the element packages at runtime if the version is needed from the package. This should be fully compatible with thedict
previously return and for most normal use cases there will be no difference. However, if some applications were relying on either mutating the contents or explicitly type checking it may require updates to adapt to this change. -
The
qiskit.execute
module has been renamed toqiskit.execute_function
. This was necessary to avoid a potentical name conflict between theexecute()
function which is re-exported asqiskit.execute
.qiskit.execute
the function in some situations could conflict withqiskit.execute
the module which would lead to a cryptic error because Python was treatingqiskit.execute
as the module when the intent was to the function or vice versa. The module rename was necessary to avoid this conflict. If you're importingqiskit.execute
to get the module (typical usage wasfrom qiskit.execute import execute
) you will need to update this to useqiskit.execute_function
instead.qiskit.execute
will now always resolve to the function. -
The
qiskit.compiler.transpile
,qiskit.compiler.assemble
,qiskit.compiler.schedule
, andqiskit.compiler.sequence
modules have been renamed toqiskit.compiler.transpiler
,qiskit.compiler.assembler
,qiskit.compiler.scheduler
, andqiskit.compiler.sequence
respectively. This was necessary to avoid a potentical name conflict between the modules and the re-exported function pathsqiskit.compiler.transpile()
,qiskit.compiler.assemble()
,qiskit.compiler.schedule()
, andqiskit.compiler.sequence()
. In some situations this name conflict between the module path and re-exported function path would lead to a cryptic error because Python was treating an import as the module when the intent was to use the function or vice versa. The module rename was necessary to avoid this conflict. If you were using the imports to get the modules before (typical usage would be like``from qiskit.compiler.transpile import transpile``) you will need to update this to use the new module paths.qiskit.compiler.transpile()
,qiskit.compiler.assemble()
,qiskit.compiler.schedule()
, andqiskit.compiler.sequence()
will now always resolve to the functions. -
The
qiskit.quantum_info.Quaternion
class was moved from theqiskit.quantum_info.operator
submodule to theqiskit.quantum_info.synthesis
submodule to better reflect it's purpose. No change is required if you were importing it from the rootqiskit.quantum_info
module, but if you were importing fromqiskit.quantum_info.operator
you will need to update your import path. -
Removed the
QuantumCircuit.mcmt
method, which has been deprecated since the Qiskit Terra 0.14.0 release in April 2020. Instead of using the method, please use theMCMT
class instead to construct a multi-control multi-target gate and use theqiskit.circuit.QuantumCircuit.append()
orqiskit.circuit.QuantumCircuit.compose()
to add it to a circuit.For example, you can replace:
circuit . mcmt ( ZGate (), [ 0 , 1 , 2 ], [ 3 , 4 ])
with:
from qiskit.circuit.library import MCMT mcmt = MCMT ( ZGate (), 3 , 2 ) circuit . compose ( mcmt , range ( 5 ))
-
Removed the
QuantumCircuit.diag_gate
method which has been deprecated since the Qiskit Terra 0.14.0 release in April 2020. Instead, use thediagonal()
method ofQuantumCircuit
. -
Removed the
QuantumCircuit.ucy
method which has been deprecated since the Qiskit Terra 0.14.0 release in April 2020. Instead, use theucry()
method ofQuantumCircuit
. -
The previously deprecated
mirror()
method forqiskit.circuit.QuantumCircuit
has been removed. It was deprecated in the 0.15.0 release. Theqiskit.circuit.QuantumCircuit.reverse_ops()
method should be used instead since mirroring could be confused with swapping the output qubits of the circuit. Thereverse_ops()
method only reverses the order of gates that are applied instead of mirroring. -
The previously deprecated support passing a float (for the
scale
kwarg as the first positional argument to theqiskit.circuit.QuantumCircuit.draw()
has been removed. It was deprecated in the 0.12.0 release. The first positional argument to theqiskit.circuit.QuantumCircuit.draw()
method is now theoutput
kwarg which does not accept a float. Instead you should be usingscale
as a named kwarg instead of using it positionally.For example, if you were previously calling
draw
with:from qiskit import QuantumCircuit qc = QuantumCircuit ( 2 ) qc . draw ( 0.75 , output = 'mpl' )
this would now need to be:
from qiskit import QuantumCircuit qc = QuantumCircuit ( 2 ) qc . draw ( output = 'mpl' , scale = 0.75 )
or:
qc . draw ( 'mpl' , scale = 0.75 )
-
Features of Qiskit Pulse (
qiskit.pulse
) which were deprecated in the 0.15.0 release (August, 2020) have been removed. The full set of changes are:Module
Old
New
qiskit.pulse.library
SamplePulse
Waveform
qiskit.pulse.library
ConstantPulse
Constant
(module rename)
pulse.pulse_lib
Moduleqiskit.pulse.library
Class
Old method
New method
ParametricPulse
get_sample_pulse
get_waveform
Instruction
command
N/A. Commands and Instructions have been unified. Use
operands()
to get information about the instruction data.Acquire
acquires
,mem_slots
,reg_slots
acquire()
,mem_slot()
,reg_slot()
. (TheAcquire
instruction no longer broadcasts across multiple qubits.) -
The dictionary previously held on
DAGCircuit
edges has been removed. Instead, edges now hold theBit
instance which had previously been included in the dictionary as its'wire'
field. Note that the NetworkX graph returned byto_networkx()
will still have a dictionary for its edge attributes, but the'name'
field will no longer be populated. -
The
parameters
attribute of theQuantumCircuit
class no longer is returning aset
. Instead it returns aParameterView
object which implements all the methods thatset
offers (albeit deprecated). This was done to support a model that preserves name-sorted parameters. It should be fully compatible with any previous usage of theset
returned by theparameters
attribute, except for where explicit type checking of a set was done. -
When running
transpile()
on aQuantumCircuit
withdelay()
instructions, the units will be converted to dt if the value of dt (sample time) is known totranspile()
, either explicitly via thedt
kwarg or via theBackendConfiguration
for aBackend
object passed in via thebackend
kwarg. -
The interpretation of
meas_map
(which is an attribute of aPulseBackendConfiguration
object or as the correspondingmeas_map
kwarg on theschedule()
,assemble()
,sequence()
, orexecute()
functions) has been updated to better match the true constraints of the hardware. The format of this data is a list of lists, where the items in the inner list are integers specifying qubit labels. For instance:[[ A , B , C ], [ D , E , F , G ]]
Previously, the
meas_map
constraint was interpreted such that if one qubit was acquired (e.g. A), then all other qubits sharing a subgroup with that qubit (B and C) would have to be acquired at the same time and for the same duration. This constraint has been relaxed. One acquisition does not require more acquisitions. (If A is acquired, B and C do not need to be acquired.) Instead, qubits in the same measurement group cannot be acquired in a partially overlapping way – think of themeas_map
as specifying a shared acquisition resource (If we acquire A fromt=1000
tot=2000
, we cannot acquire B starting from1000<t<2000
). For example:# Good meas_map = [[ 0 , 1 ]] # Acquire a subset of [0, 1] sched = pulse . Schedule () sched = sched . append ( pulse . Acquire ( 10 , acq_q0 )) # Acquire 0 and 1 together (same start time, same duration) sched = pulse . Schedule () sched = sched . append ( pulse . Acquire ( 10 , acq_q0 )) sched = sched . append ( pulse . Acquire ( 10 , acq_q1 )) # Acquire 0 and 1 disjointly sched = pulse . Schedule () sched = sched . append ( pulse . Acquire ( 10 , acq_q0 )) sched = sched . append ( pulse . Acquire ( 10 , acq_q1 )) << 10 # Acquisitions overlap, but 0 and 1 aren't in the same measurement # grouping meas_map = [[ 0 ], [ 1 ]] sched = pulse . Schedule () sched = sched . append ( pulse . Acquire ( 10 , acq_q0 )) sched = sched . append ( pulse . Acquire ( 10 , acq_q1 )) << 1 # Bad: 0 and 1 are in the same grouping, but acquisitions # partially overlap meas_map = [[ 0 , 1 ]] sched = pulse . Schedule () sched = sched . append ( pulse . Acquire ( 10 , acq_q0 )) sched = sched . append ( pulse . Acquire ( 10 , acq_q1 )) << 1
Deprecation Notes¶
-
Two new arguments have been added to
qiskit.dagcircuit.DAGNode.semantic_eq()
,bit_indices1
andbit_indices2
, which are expected to map theBit
instances in eachDAGNode
to their index inqubits
orclbits
list of their respectiveDAGCircuit
. During the deprecation period, these arguments are optional and when not specified the mappings will be automatically constructed based on theregister
andindex
properties of eachBit
instance. However, in a future release, they will be required arguments and the mapping will need to be supplied by the user. -
The
pulse
builder functions:-
qiskit.pulse.call_circuit()
-
qiskit.pulse.call_schedule()
are deprecated and will be removed in a future release. These functions are unified into
qiskit.pulse.call()
which should be used instead. -
-
The
qiskit.pulse.Schedule
methodqiskit.pulse.Schedule.flatten()
method is deprecated and will be removed in a future release. Instead you can use theqiskit.pulse.transforms.flatten()
function which will perform the same operation. -
The
assign_parameters()
for the following classes:-
qiskit.pulse.channels.Channel
, -
qiskit.pulse.library.Pulse
, -
qiskit.pulse.instructions.Instruction
,
and all their subclasses is now deprecated and will be removed in a future release. This functionality has been subsumed
ScheduleBlock
which is the future direction for constructing parameterized pulse programs. -
-
The
parameters
attribute for the following clasess:-
Channel
-
Instruction
.
is deprecated and will be removed in a future release. This functionality has been subsumed
ScheduleBlock
which is the future direction for constructing parameterized pulse programs. -
-
Python 3.6 support has been deprecated and will be removed in a future release. When support is removed you will need to upgrade the Python version you're using to Python 3.7 or above.
-
Two
QuantumCircuit
methodscombine()
andextend()
along with their corresponding Python operators+
and+=
are deprecated and will be removed in a future release. Instead theQuantumCircuit
methodcompose()
should be used. Thecompose()
method allows more flexibility in composing two circuits that do not have matching registers. It does not, however, automatically add qubits/clbits unlike the deprecated methods. To add a circuit on new qubits/clbits, theqiskit.circuit.QuantumCircuit.tensor()
method can be used. For example:from qiskit.circuit import QuantumRegister , QuantumCircuit a = QuantumRegister ( 2 , 'a' ) circuit_a = QuantumCircuit ( a ) circuit_a . cx ( 0 , 1 ) b = QuantumRegister ( 2 , 'b' ) circuit_b = QuantumCircuit ( b ) circuit_b . cz ( 0 , 1 ) # same as circuit_a + circuit_b (or combine) added_with_different_regs = circuit_b . tensor ( circuit_a ) # same as circuit_a + circuit_a (or combine) added_with_same_regs = circuit_a . compose ( circuit_a ) # same as circuit_a += circuit_b (or extend) circuit_a = circuit_b . tensor ( circuit_a ) # same as circuit_a += circuit_a (or extend) circuit_a . compose ( circuit_a , inplace = True )
-
Support for passing
Qubit
instances to thequbits
kwarg of theqiskit.transpiler.InstructionDurations.get()
method has been deprecated and will be removed in a future release. Instead, you should call theget()
method with the integer indices of the desired qubits. -
Using
@
(__matmul__
) for invoking thecompose
method ofBaseOperator
subclasses (egOperator
) is deprecated and will be removed in a future release. Theqiskit.quantum_info.Operator.compose()
method can be used directly or also invoked using the&
(__and__
) operator. -
Using
*
(__mul__
) for calling thedot()
method ofBaseOperator
subclasses (egqiskit.quantum_info.Operator
) is deprecated and will be removed in a future release. Instead you can just call thedot()
directly. -
Using
@
(__matmul__
) for invoking theevolve()
method of theqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes is deprecated and will be removed in a future release.. Theevolve
method can be used directly or also invoked using the&
(__and__
) operator. -
The
qiskit.pulse.schedule.ParameterizedSchedule
class has been deprecated and will be removed in a future release. Instead you can directly parameterize pulseSchedule
objects with aParameter
object, for example:from qiskit.circuit import Parameter from qiskit.pulse import Schedule from qiskit.pulse import ShiftPhase , DriveChannel theta = Parameter ( 'theta' ) target_schedule = Schedule () target_schedule . insert ( 0 , ShiftPhase ( theta , DriveChannel ( 0 )), inplace = True )
-
The
qiskit.pulse.ScheduleComponent
class in theqiskit.pulse
module has been deprecated and will be removed in a future release. Its usage should be replaced either using aqiskit.pulse.Schedule
orqiskit.pulse.Instruction
directly. Additionally, the primary purpose of theScheduleComponent
class was as a common base class for bothSchedule
andInstruction
for any place that was explicitly type checking or documenting accepting aScheduleComponent
input should be updated to acceptInstruction
orSchedule
. -
The JSON Schema files and usage for the IBMQ API payloads are deprecated and will be removed in a future release. This includes everything under the
qiskit.schemas
module and theqiskit.validation
module. This also includes thevalidate
kwargs forqiskit.qobj.QasmQobj.to_dict()
andqiskit.qobj.QasmQobj.to_dict()
along with the module level fastjsonschema validators inqiskit.qobj
(which do not raise a deprecation warning). The schema files have been moved to the Qiskit/ibmq-schemas repository and those should be treated as the canonical versions of the API schemas. Moving forward only those schemas will recieve updates and will be used as the source of truth for the schemas. If you were relying on the schemas bundled in qiskit-terra you should update to use that repository instead. -
The
qiskit.util
module has been deprecated and will be removed in a future release. It has been replaced byqiskit.utils
which provides the same functionality and will be expanded in the future. Note that noDeprecationWarning
will be emitted regarding this deprecation since it was not feasible on Python 3.6. -
The
CXDirection
transpiler pass in theqiskit.transpiler.passes
module has been deprecated and will be removed in a future release. Instead theGateDirection
should be used. It behaves identically to theCXDirection
except that it now also supports transforming a circuit withECRGate
gates in addition toCXGate
gates. -
The
CheckCXDirection
transpiler pass in theqiskit.transpiler.passes
module has been deprecated and will be removed in a future release. Instead theCheckGateDirection
pass should be used. It behaves identically to theCheckCXDirection
except that it now also supports checking the direction of all 2-qubit gates, not justCXGate
gates. -
The
WeightedAdder
methodnum_ancilla_qubits()
is deprecated and will be removed in a future release. It has been replaced with theqiskit.circuit.library.WeightedAdder.num_ancillas
attribute which is consistent with other circuit libraries' APIs. -
The following legacy methods of the
qiskit.quantum_info.Pauli
class have been deprecated. See the method documentation for replacement use in the updated Pauli class.-
from_label()
-
sgn_prod()
-
to_spmatrix()
-
kron()
-
update_z()
-
update_x()
-
insert_paulis()
-
append_paulis()
-
delete_qubits()
-
pauli_single()
-
random()
-
-
Using a
list
ornumpy.ndarray
as thechannel
ortarget
argument for theqiskit.quantum_info.process_fidelity()
,qiskit.quantum_info.average_gate_fidelity()
,qiskit.quantum_info.gate_error()
, andqiskit.quantum_info.diamond_norm()
functions has been deprecated and will not be supported in a future release. The inputs should instead be aGate
or aBaseOperator
subclass object (eg.Operator
,Choi
, etc.) -
Accessing references from
Qubit
andClbit
instances to their containing registers via theregister
orindex
properties has been deprecated and will be removed in a future release. Instead,Register
objects can be queried to find theBit
objects they contain. -
The current functionality of the
qiskit.visualization.pulse_drawer()
function is deprecated and will be replaced byqiskit.visualization.pulse_drawer_v2()
(which is not backwards compatible) in a future release. -
The use of methods inherited from the
set
type on the output of theparameters
attribute (which used to be aset
) of theQuantumCircuit
class are deprecated and will be removed in a future release. This includes the methods from theadd()
,difference()
,difference_update()
,discard()
,intersection()
,intersection_update()
,issubset()
,issuperset()
,symmetric_difference()
,symmetric_difference_update()
,union()
,update()
,__isub__()
(which is the-=
operator), and__ixor__()
(which is the^=
operator). -
The name of the first (and only) positional argument for the
qiskit.circuit.QuantumCircuit.bind_parameters()
method has changed fromvalue_dict
tovalues
. The passing an argument in with the namevalues_dict
is deprecated and will be removed in future release. For example, if you were previously callingbind_parameters()
with a call like:bind_parameters(values_dict={})
this is deprecated and should be replaced bybind_parameters(values={})
or even better just pass the argument positionallybind_parameters({})
. -
The name of the first (and only) positional argument for the
qiskit.circuit.QuantumCircuit.assign_parameters()
method has changed fromparam_dict
toparameters
. Passing an argument in with the nameparam_dict
is deprecated and will be removed in future release. For example, if you were previously callingassign_parameters()
with a call like:assign_parameters(param_dict={})
this is deprecated and should be replaced byassign_parameters(values={})
or even better just pass the argument positionallyassign_parameters({})
.
Bug Fixes¶
-
Fixed an issue where the
execute()
function would raiseQiskitError
exception when aParameterVector
object was passed in for theparameter_bind
kwarg. parameter. For example, it is now possible to call something like:execute ( circuit , backend , parameter_binds = [{ pv1 : [ ... ], pv2 : [ ... ]}])
where
pv1
andpv2
areParameterVector
objects. Fixed #5467 -
Fixed an issue with the labels of parametric pulses in the
PulseQobjInstruction
class were not being properly set as they are with sampled pulses. This also means that pulse names that are imported from thePulseDefaults
returned by aBackend
, such asx90
,x90m
, etc, will properly be set. Fixed #5363 -
Fixed an issue where unbound parameters only occurring in the
global_phase
attribute of aQuantumCircuit
object would not show in theparameters
attribute and could not be bound. Fixed #5806 -
The
calibrations
attribute ofQuantumCircuit
objects are now preserved when the+=
(ie theextend()
method) and the+
(ie thecombine()
method) are used. Fixed #5930 and #5908 -
The
name
setter method of classRegister
(which is the parent class ofQuantumRegister
andClassicalRegister
) previously did not check if the assigned string was a valid register name as per the OpenQASM specification. This check was previously only performed when the name was specified in the constructor, this has now been fixed so that setting thename
attribute directly with an invalid value will now also raise an exception. Fixed #5461 -
Fixed an issue with the
qiskit.visualization.circuit_drawer()
function andqiskit.circuit.QuantumCircuit.draw()
method when visualizing aQuantumCircuit
with aGate
that has a classical condition after aMeasure
that used the sameClassicalRegister
, it was possible for the conditionalGate
to be displayed to the left of theMeasure
. Fixed #5387 -
In the transpiler pass
qiskit.transpiler.passes.CSPLayout
a bias towards lower numbered qubits could be observed. This undesireable bias has been fixed by shuffling the candidates to randomize the results. Furthermore, the usage of theCSPLayout
pass in thepreset_passmanagers
(for level 2 and 3) has been adjusted to use a configured seed if theseed_transpiler
kwarg is set whentranspile()
is called. Fixed #5990 -
Fixes a bug where the
channels
field for aPulseBackendConfiguration
object was not being included in the output of theqiskit.providers.models.PulseBackendConfiguration.to_dict
method. Fixed #5579 -
Fixed the
'circular'
entanglement in theqiskit.circuit.library.NLocal
circuit class for the edge case where the circuit has the same size as the entanglement block (e.g. a two-qubit circuit and CZ entanglement gates). In this case there should only be one entanglement gate, but there was accidentially added a second one in the inverse direction as the first. Fixed Qiskit/qiskit-aqua#1452 -
Fixed the handling of breakpoints in the
PiecewisePolynomialPauliRotations
class in theqiskit.circuit.library
. Now forn
intervals,n+1
breakpoints are allowed. This enables specifying another end interval other than \(2^\text{num qubits}\). This is important because from the end of the last interval to \(2^\text{num qubits}\) the function is the identity. -
Fixed an issue in the
qiskit.circuit.library.Permutation
circuit class where some permutations would not be properly generated. This issue could also effectqiskit.circuit.library.QuantumVolume
if it were called with classical_permutation=False`. Fixed #5812 -
Fixed an issue where generating QASM output with the
qasm()
method for aQuantumCircuit
object that has aControlledGate
with an open control the output would be as if all controls were closed independent of the specified control state. This would result in a different circuit being created fromfrom_qasm_str()
if parsing the generated QASM.This was fixed by updating the QASM output from
qasm()
by defining a composite gate which usesXGate
to implement the open controls. The composite gate is named like<original_gate_name>_o<ctrl_state>
whereo
stands for open control andctrl_state
is the integer value of the control state. Fixed #5443 -
Fixed an issue where binding
Parameter
objects in aQuantumCircuit
with theparameter_binds
in theexecute
function would cause all the boundQuantumCircuit
objects would have the samename
, which meant the result names were also not unique. This fix causes thebind_parameters()
andassign_parameters()
to assign a unique circuit name wheninplace=False
as:< base name >-< class instance no .> [ -< pid name > ]
where
<base name>
is the name supplied by the "name" kwarg, otherwise it defaults to "circuit". The class instance number gets incremented every time an instance of the class is generated.<pid name>
is appended if called outside the main process. Fixed #5185 -
Fixed an issue with the
scheduler()
function where it would raise an exception if an input circuit contained an unboundQuantumCircuit
object. Fixed #5304 -
Fixed an issue in the
qiskit.transpiler.passes.TemplateOptimization
transpiler passes where template circuits that contained unboundParameter
objects would crash under some scenarios if the parameters could not be bound during the template matching. Now, if theParameter
objects can not be bound templates with unboundParameter
are discarded and ignored by theTemplateOptimization
pass. Fixed #5533 -
Fixed an issue with the
qiskit.visualization.timeline_drawer()
function where classical bits were inproperly handled. Fixed #5361 -
Fixed an issue in the
qiskit.visualization.circuit_drawer()
function and theqiskit.circuit.QuantumCircuit.draw()
method whereDelay
instructions in aQuantumCircuit
object were not being correctly treated as idle time. So when theidle_wires
kwarg was set toFalse
the wires with theDelay
objects would still be shown. This has been fixed so that the idle wires are removed from the visualization if there are onlyDelay
objects on a wire. -
Previously, when the option
layout_method
kwarg was provided to thetranspile()
function and theoptimization_level
kwarg was set to >= 2 so that the passqiskit.transpiler.passes.CSPLayout
would run, ifCSPLayout
found a solution then the method inlayout_method
was not executed. This has been fixed so that if specified, thelayout_method
is always honored. Fixed #5409 -
When the argument
coupling_map=None
(either set explicitly, set implicitly as the default value, or via thebackend
kwarg), the transpiling process was not "embedding" the circuit. That is, even when aninitial_layout
was specified, the virtual qubits were not assigned to physical qubits. This has been fixed so that now, theqiskit.compiler.transpile()
function honors theinitial_layout
argument by embedding the circuit:from qiskit import QuantumCircuit , QuantumRegister from qiskit.compiler import transpile qr = QuantumRegister ( 2 , name = 'qr' ) circ = QuantumCircuit ( qr ) circ . h ( qr [ 0 ]) circ . cx ( qr [ 0 ], qr [ 1 ]) transpile ( circ , initial_layout = [ 1 , 0 ]) . draw ( output = 'mpl' )
If the
initial_layout
refers to more qubits than in the circuit, the transpiling process will extended the circuit with ancillas.from qiskit import QuantumCircuit , QuantumRegister from qiskit.compiler import transpile qr = QuantumRegister ( 2 , name = 'qr' ) circ = QuantumCircuit ( qr ) circ . h ( qr [ 0 ]) circ . cx ( qr [ 0 ], qr [ 1 ]) transpile ( circ , initial_layout = [ 4 , 2 ], coupling_map = None ) . draw ()
ancilla_0 -> 0 ────────── ancilla_1 -> 1 ────────── ┌───┐ qr_1 -> 2 ─────┤ X ├ └─┬─┘ ancilla_2 -> 3 ───────┼── ┌───┐ │ qr_0 -> 4 ┤ H ├──■── └───┘
Fixed #5345
-
A new kwarg,
user_cost_dict
has been added to the constructor for theqiskit.transpiler.passes.TemplateOptimization
transpiler pass. This enables users to provide a custom cost dictionary for the gates to the underlying template matching algorithm. For example:from qiskit.transpiler.passes import TemplateOptimization cost_dict = { 'id' : 0 , 'x' : 1 , 'y' : 1 , 'z' : 1 , 'h' : 1 , 't' : 1 } pass = TemplateOptimization ( user_cost_dict = cost_dict )
-
An issue when passing the
Counts
object returned byget_counts()
tomarginal_counts()
would produce an improperly formattedCounts
object with certain inputs has been fixed. Fixes #5424 -
Improved the allocation of helper qubits in
PolynomialPauliRotations
andPiecewiseLinearPauliRotations
which makes the implementation of these circuit more efficient. Fixed #5320 and #5322 -
Fix the usage of the allocated helper qubits in the
MCXGate
in theWeightedAdder
class. These were previously allocated but not used prior to this fix. Fixed #5321 -
In a number of cases, the
latex
output method for theqiskit.visualization.circuit_drawer()
function and thedraw()
method did not display the gate name correctly, and in other cases, did not include gate parameters where they should be. Now the gate names will be displayed the same way as they are displayed with thempl
output method, and parameters will display for all the gates that have them. In addition, some of the gates did not display in the correct form, and these have been fixed. Fixes #5605, #4938, and #3765 -
Fixed an issue where, if the
qiskit.circuit.Instruction.to_instruction()
method was used on a subcircuit which contained classical registers and thatInstruction
object was then added to aQuantumCircuit
object, then the output from theqiskit.visualization.circuit_drawer()
function and theqiskit.circuit.QuantumCircuit.draw()
method would in some instances display the subcircuit to the left of a measure when it should have been displayed to the right. Fixed #5947 -
Fixed an issue with
Delay
objects in aQuantumCircuit
whereqiskit.compiler.transpile()
would not be convert the units of theDelay
to the units of theBackend
, if thebackend
kwarg is set ontranspile()
. This could result in the wrong behavior because of a unit mismatch, for example running:from qiskit import transpile , execute from qiskit.circuit import QuantumCircuit qc = QuantumCircuit ( 1 ) qc . delay ( 100 , [ 0 ], unit = 'us' ) qc = transpile ( qc , backend ) job = execute ( qc , backend )
would previously have resulted in the backend delay for 100 timesteps (each of duration dt) rather than expected (100e-6 / dt) timesteps. This has been corrected so the
qiskit.compiler.transpile()
function properly converts the units.
Other Notes¶
-
The snapshots of all the fake/mock backends in
qiskit.test.mock
have been updated to reflect recent device changes. This includes a change in thebasis_gates
attribute for theBackendConfiguration
to['cx', 'rz', 'sx', 'x', 'id']
, the addition of areadout_length
property to the qubit properties in theBackendProperties
, and updating thePulseDefaults
so that all the mock backends support parametric pulse basedInstructionScheduleMap
instances.
Aer 0.8.0¶
Prelude¶
The 0.8 release includes several new features and bug fixes. The highlights for this release are: the introduction of a unified AerSimulator
backend for running circuit simulations using any of the supported simulation methods; a simulator instruction library ( qiskit.providers.aer.library
) which includes custom instructions for saving various kinds of simulator data; MPI support for running large simulations on a distributed computing environment.
New Features¶
-
Python 3.9 support has been added in this release. You can now run Qiskit Aer using Python 3.9 without building from source.
-
Add the CMake flag
DISABLE_CONAN
(default=``OFF``)s. When installing from source, setting this toON
allows bypassing the Conan package manager to find libraries that are already installed on your system. This is also available as an environment variableDISABLE_CONAN
, which takes precedence over the CMake flag. This is not the official procedure to build AER. Thus, the user is responsible of providing all needed libraries and corresponding files to make them findable to CMake. -
This release includes support for building qiskit-aer with MPI support to run large simulations on a distributed computing environment. See the contributing guide for instructions on building and running in an MPI environment.
-
It is now possible to build qiskit-aer with CUDA enabled in Windows. See the contributing guide for instructions on building from source with GPU support.
-
When building the qiskit-aer Python extension from source several build dependencies need to be pre-installed to enable C++ compilation. As a user convenience when building the extension any of these build dependencies which were missing would be automatically installed using
pip
prior to the normalsetuptools
installation steps, however it was previously was not possible to avoid this automatic installation. To solve this issue a new environment variableDISABLE_DEPENDENCY_INSTALL
has been added. If it is set to1
orON
when building the python extension from source this will disable the automatic installation of these missing build dependencies. -
Adds support for optimized N-qubit Pauli gate (
qiskit.circuit.library.PauliGate
) to theStatevectorSimulator
,UnitarySimulator
, and the statevector and density matrix methods of theQasmSimulator
andAerSimulator
. -
The
run()
method for theAerSimulator
,QasmSimulator
,StatevectorSimulator
, andUnitarySimulator
backends now takes aQuantumCircuit
(or a list ofQuantumCircuit
objects) as it's input. The previousQasmQobj
object is still supported for now, but will be deprecated in a future release.For an example of how to use this see:
from qiskit import transpile , QuantumCircuit from qiskit.providers.aer import Aer backend = Aer . get_backend ( 'aer_simulator' ) circuit = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc . measure_all () tqc = transpile ( circuit , backend ) result = backend . run ( tqc , shots = 4096 ) . result ()
-
The
run()
method for thePulseSimulator
backend now takes aSchedule
(or a list ofSchedule
objects) as it's input. The previousPulseQobj
object is still supported for now, but will be deprecated in a future release. -
Adds the new
AerSimulator
simulator backend supporting the following simulation methods-
automatic
-
statevector
-
stabilizer
-
density_matrix
-
matrix_product_state
-
unitary
-
superop
The default automatic method will automatically choose a simulation method separately for each run circuit based on the circuit instructions and noise model (if any). Initializing a simulator with a specific method can be done using the method option.
GPU simulation for the statevector, density matrix and unitary methods can be enabled by setting the
device='GPU'
backend option.Note that the
unitary
andsuperop
methods do not support measurement as they simulate the unitary matrix or superoperator matrix of the run circuit so one of the newsave_unitary()
,save_superop()
, orsave_state()
instructions must be used to save the simulator state to the returned results. Similarly state of the other simulations methods can be saved using the appropriate instructions. See theqiskit.providers.aer.library
API documents for more details.Note that the
AerSimulator
simulator superceds theQasmSimulator
,StatevectorSimulator
, andUnitarySimulator
backends which will be deprecated in a future release. -
-
Updates the
AerProvider
class to include multipleAerSimulator
backends preconfigured for all available simulation methods and simulation devices. The new backends can be accessed through the provider interface using the names-
"aer_simulator"
-
"aer_simulator_statevector"
-
"aer_simulator_stabilizer"
-
"aer_simulator_density_matrix"
-
"aer_simulator_matrix_product_state"
-
"aer_simulator_extended_stabilizer"
-
"aer_simulator_unitary"
-
"aer_simulator_superop"
Additional if Aer was installed with GPU support on a compatible system the following GPU backends will also be available
-
"aer_simulator_statevector_gpu"
-
"aer_simulator_density_matrix_gpu"
-
"aer_simulator_unitary_gpu"
For example:
from qiskit import Aer # Get the GPU statevector simulator backend backend = Aer . get_backend ( 'aer_simulator_statevector_gpu' )
-
-
Added a new
norm estimation
method for performing measurements when using the"extended_stabilizer"
simulation method. This norm estimation method can be used by passing the following options to theAerSimulator
andQasmSimulator
backendssimulator = QasmSimulator ( method = 'extended_stabilizer' , extended_stabilizer_sampling_method = 'norm_estimation' )
The norm estimation method is slower than the alternative
metropolis
orresampled_metropolis
options, but gives better performance on circuits with sparse output distributions. See the documentation of theQasmSimulator
for more information. -
Adds instructions for saving the state of the simulator in various formats. These instructions are
-
qiskit.providers.aer.library.SaveDensityMatrix
-
qiskit.providers.aer.library.SaveMatrixProductState
-
qiskit.providers.aer.library.SaveStabilizer
-
qiskit.providers.aer.library.SaveState
-
qiskit.providers.aer.library.SaveStatevector
-
qiskit.providers.aer.library.SaveStatevectorDict
-
qiskit.providers.aer.library.SaveUnitary
These instructions can be appended to a quantum circuit by using the
save_density_matrix
,save_matrix_product_state
,save_stabilizer
,save_state
,save_statevector
,save_statevector_dict
,save_unitary
circuit methods which are added toQuantumCircuit
when importing Aer.See the
qiskit.providers.aer.library
API documentation for details on method compatibility for each instruction.Note that the snapshot instructions
SnapshotStatevector
,SnapshotDensityMatrix
,SnapshotStabilizer
are still supported but will be deprecated in a future release. -
-
Adds
qiskit.providers.aer.library.SaveExpectationValue
andqiskit.providers.aer.library.SaveExpectationValueVariance
quantum circuit instructions for saving the expectation value \(\langle H\rangle = Tr[H\rho]\), or expectation value and variance \(Var(H) = \langle H^2\rangle - \langle H\rangle^2\), of a Hermitian operator \(H\) for the simulator state \(\rho\). These instruction can be appended to a quantum circuit by using thesave_expectation_value
andsave_expectation_value_variance
circuit methods which is added toQuantumCircuit
when importing Aer.Note that the snapshot instruction
SnapshotExpectationValue
, is still supported but will be deprecated in a future release. -
Adds
qiskit.providers.aer.library.SaveProbabilities
andqiskit.providers.aer.library.SaveProbabilitiesDict
quantum circuit instruction for saving all measurement outcome probabilities for Z-basis measurements of the simualtor state. These instruction can be appended to a quantum circuit by using thesave_probabilities
andsave_probabilities_dict
circuit methods which is added toQuantumCircuit
when importing Aer.Note that the snapshot instruction
SnapshotProbabilities
, is still supported but will be deprecated in a future release. -
Adds
qiskit.providers.aer.library.SaveAmplitudes
andqiskit.providers.aer.library.SaveAmplitudesSquared
circuit instructions for saving select complex statevector amplitudes, or select probabilities (amplitudes squared) for supported simulation methods. These instructions can be appended to a quantum circuit by using thesave_amplitudes
andsave_amplitudes_squared
circuit methods which is added toQuantumCircuit
when importing Aer. -
Adds instructions for setting the state of the simulators. These instructions must be defined on the full number of qubits in the circuit. They can be applied at any point in a circuit and will override the simulator state with the one specified. Added instructions are
-
qiskit.providers.aer.library.SetDensityMatrix
-
qiskit.providers.aer.library.SetStabilizer
-
qiskit.providers.aer.library.SetStatevector
-
qiskit.providers.aer.library.SetUnitary
These instruction can be appended to a quantum circuit by using the
set_density_matrix
,set_stabilizer
,set_statevector
,set_unitary
circuit methods which are added toQuantumCircuit
when importing Aer.See the
qiskit.providers.aer.library
API documentation for details on method compatibility for each instruction. -
-
Added support for diagonal gates to the
"matrix_product_state"
simulation method. -
Added support for the
initialize
instruction to the"matrix_product_state"
simulation method.
Known Issues¶
-
There is a known issue where the simulation of certain circuits with a Kraus noise model using the
"matrix_product_state"
simulation method can cause the simulator to crash. Refer to #306 for more information.
Upgrade Notes¶
-
The minimum version of Conan has been increased to 1.31.2. This was necessary to fix a compatibility issue with newer versions of the urllib3 (which is a dependency of Conan). It also adds native support for AppleClang 12 which is useful for users with new Apple computers.
-
pybind11
minimum version required is 2.6 instead of 2.4. This is needed in order to support CUDA enabled compilation in Windows. -
Cython has been removed as a build dependency.
-
Removed x90 gate decomposition from noise models that was deprecated in qiskit-aer 0.7. This decomposition is now done by using regular noise model basis gates and the qiskit transpiler.
-
The following options for the
"extended_stabilizer"
simulation method have changed.-
extended_stabilizer_measure_sampling
: This option has been replaced by the optionsextended_stabilizer_sampling_method
, which controls how we simulate qubit measurement. -
extended_stabilizer_mixing_time
: This option has been renamed asextended_stabilizer_metropolis_mixing_time
to clarify it only applies to themetropolis
andresampled_metropolis
sampling methods. -
extended_stabilizer_norm_estimation_samples
: This option has been renamed toextended_stabilizer_norm_estimation_default_samples
.
One additional option,
extended_stabilizer_norm_estimation_repetitions
has been added, whih controls part of the behaviour of the norm estimation sampling method. -
Deprecation Notes¶
-
Python 3.6 support has been deprecated and will be removed in a future release. When support is removed you will need to upgrade the Python version you're using to Python 3.7 or above.
Bug Fixes¶
-
Fixes bug with
AerProvider
where options set on the returned backends usingset_options()
were stored in the provider and would persist for subsequent calls toget_backend()
for the same named backend. Now every call to andbackends()
returns a new instance of the simulator backend that can be configured. -
Fixes bug in the error message returned when a circuit contains unsupported simulator instructions. Previously some supported instructions were also being listed in the error message along with the unsupported instructions.
-
Fixes issue with setting
QasmSimulator
basis gates when using"method"
and"noise_model"
options together, and when using them with a simulator constructed usingfrom_backend()
. Now the listed basis gates will be the intersection of gates supported by the backend configuration, simulation method, and noise model basis gates. If the intersection of the noise model basis gates and simulator basis gates is empty a warning will be logged. -
Fix bug where the
"sx"`
gateSXGate
was not listed as a supported gate in the C++ code, inStateOpSet
ofmatrix_product_state.hp
. -
Fix bug where
"csx"
,"cu2"
,"cu3"
were incorrectly listed as supported basis gates for the"density_matrix"
method of theQasmSimulator
. -
Fix bug where parameters were passed incorrectly between functions in
matrix_product_state_internal.cpp
, causing wrong simulation, as well as reaching invalid states, which in turn caused an infinite loop. -
Fixes a bug that resulted in
c_if
not working when the width of the conditional register was greater than 64. See #1077. -
Fixes a bug #1153) where noise on conditional gates was always being applied regardless of whether the conditional gate was actually applied based on the classical register value. Now noise on a conditional gate will only be applied in the case where the conditional gate is applied.
-
Fixes a bug with nested OpenMP flag was being set to true when it shouldn't be.
-
Fixes a bug when applying truncation in the matrix product state method of the QasmSimulator.
-
Fixed issue #1126: bug in reporting measurement of a single qubit. The bug occured when copying the measured value to the output data structure.
-
In MPS, apply_kraus was operating directly on the input bits in the parameter qubits, instead of on the internal qubits. In the MPS algorithm, the qubits are constantly moving around so all operations should be applied to the internal qubits.
-
When invoking MPS::sample_measure, we need to first sort the qubits to the default ordering because this is the assumption in qasm_controller.This is done by invoking the method move_all_qubits_to_sorted_ordering. It was correct in sample_measure_using_apply_measure, but missing in sample_measure_using_probabilities.
-
Fixes bug with the
from_backend()
method of theQasmSimulator
that would set thelocal
attribute of the configuration to the backend value rather than always being set toTrue
. -
Fixes bug in
from_backend()
andfrom_backend()
wherebasis_gates
was set incorrectly for IBMQ devices with basis gate set['id', 'rz', 'sx', 'x', 'cx']
. Now the noise model will always have the same basis gates as the backend basis gates regardless of whether those instructions have errors in the noise model or not. -
Fixes an issue where the Extended "extended_stabilizer" simulation method would give incorrect results on quantum circuits with sparse output distributions. Refer to #306 for more information and examples.
Ignis 0.6.0¶
Upgrade Notes¶
-
The
qiskit.ignis.verification.randomized_benchmarking_seq()
function is now using the upgraded CNOTDihedral class,qiskit.ignis.verification.CNOTDihedral
, which enables performing CNOT-Dihedral Randomized Benchmarking on more than two qubits. -
The python package
retworkx
is now a requirement for installing qiskit-ignis. It replaces the previous usage ofnetworkx
(which is no longer a requirement) to get better performance. -
The
scikit-learn
dependency is no longer required and is now an optional requirement. If you're using the IQ measurement discriminators (IQDiscriminationFitter
,LinearIQDiscriminationFitter
,QuadraticIQDiscriminationFitter
, orSklearnIQDiscriminator
) you will now need to manually install scikit-learn, either by runningpip install scikit-learn
or when you're also installing qiskit-ignis withpip install qiskit-ignis[iq]
.
Bug Fixes¶
-
Fixed an issue in the expectation value method
expectation_value()
, for the error mitigation classesTensoredExpvalMeasMitigator
andCTMPExpvalMeasMitigator
if thequbits
kwarg was not specified it would incorrectly use the total number of qubits of the mitigator, rather than the number of classical bits in the count dictionary leading to greatly reduced performance. Fixed #561 -
Fix the
"auto"
method of theTomographyFitter
,StateTomographyFitter
, andProcessTomographyFitter
to only use"cvx"
if CVXPY is installed and a third-party SDP solver other than SCS is available. This is because the SCS solver has lower accuracy than other solver methods and often returns a density matrix or Choi-matrix that is not completely-positive and fails validation when used with theqiskit.quantum_info.state_fidelity()
orqiskit.quantum_info.process_fidelity()
functions.
Aqua 0.9.0¶
This release officially deprecates the Qiskit Aqua project, in the future (no sooner than 3 months from this release) the Aqua project will have it's final release and be archived. All the functionality that qiskit-aqua provides has been migrated to either new packages or to other qiskit packages. The application modules that are provided by qiskit-aqua have been split into several new packages: qiskit-optimization
, qiskit-nature
, qiskit-machine-learning
, and qiskit-finance
. These packages can be installed by themselves (via the standard pip install command, ie pip install qiskit-nature
) or with the rest of the Qiskit metapackage as optional extras (ie, pip install 'qiskit[finance,optimization]'
or pip install 'qiskit[all]'
. The core building blocks for algorithms and the operator flow now exist as part of qiskit-terra at qiskit.algorithms
and qiskit.opflow
. Depending on your existing usage of Aqua you should either use the application packages or the new modules in Qiskit Terra.
For more details on how to migrate from using Qiskit Aqua you can refer to the aqua-migration.
IBM Q Provider 0.12.2¶
No change
Qiskit 0.24.1¶
IBM Q Provider 0.12.2¶
Upgrade Notes¶
-
qiskit.providers.ibmq.IBMQBackend.defaults()
now returns the pulse defaults for the backend if the backend supports pulse. However, your provider may not support pulse even if the backend does. Theopen_pulse
flag in backend configuration indicates whether the provider supports it.
Qiskit 0.24.0¶
Aer 0.7.6¶
New Features¶
-
This is the first release of qiskit-aer that publishes precompiled binaries to PyPI for Linux on aarch64 (arm64). From this release onwards Linux aarch64 packages will be published and supported.
Bug Fixes¶
-
Fixes a bug #1153 where noise on conditional gates was always being applied regardless of whether the conditional gate was actually applied based on the classical register value. Now noise on a conditional gate will only be applied in the case where the conditional gate is applied.
-
Fixed issue #1126: bug in reporting measurement of a single qubit. The bug occured when copying the measured value to the output data structure.
-
There was previously a mismatch between the default reported number of qubits the Aer backend objects would say were supported and the the maximum number of qubits the simulator would actually run. This was due to a mismatch between the Python code used for calculating the max number of qubits and the C++ code used for a runtime check for the max number of qubits based on the available memory. This has been correct so by default now Aer backends will allow running circuits that can fit in all the available system memory. Fixes #1114
No change
IBM Q Provider 0.12.0¶
New Features¶
-
Python 3.9 support has been added in this release. You can now run Qiskit IBMQ provider using Python 3.9.
-
qiskit.providers.ibmq.AccountProvider.backends()
now has a new parameter min_num_qubits that allows you to filter by the minimum number of qubits. -
qiskit.providers.ibmq.IBMQBackend.run()
method now takes one or moreQuantumCircuit
orSchedule
. Runtime configuration options, such as the number of shots, can be set via either therun()
method, or theqiskit.providers.ibmq.IBMQBackend.set_options()
method. The former is used as a one-time setting for the job, and the latter for all jobs sent to the backend. If an option is set in both places, the value set inrun()
takes precedence. For example:from qiskit import IBMQ , transpile from qiskit.test.reference_circuits import ReferenceCircuits provider = IBMQ . load_account () backend = provider . get_backend ( 'ibmq_vigo' ) circuits = transpile ( ReferenceCircuits . bell (), backend = backend ) default_shots = backend . options . shots # Returns the backend default of 1024 shots. backend . set_options ( shots = 2048 ) # All jobs will now have use 2048 shots. backend . run ( circuits ) # This runs with 2048 shots. backend . run ( circuits , shots = 8192 ) # This runs with 8192 shots. backend . run ( circuits ) # This again runs with 2048 shots.
-
qiskit.providers.ibmq.experiment.Experiment
now has three additional attributes, hub, group, and project, that identify the provider used to create the experiment. -
You can now assign an
experiment_id
to a job when submitting it usingqiskit.providers.ibmq.IBMQBackend.run()
. You can use this new field to group together a collection of jobs that belong to the same experiment. Theqiskit.providers.ibmq.IBMQBackendService.jobs()
method was also updated to allow filtering byexperiment_id
. -
qiskit.providers.ibmq.experiment.Experiment
now has two additional attributes:-
share_level: The level at which the experiment is shared which determines who can see it when listing experiments. This can be updated.
-
owner: The ID of the user that uploaded the experiment. This is set by the server and cannot be updated.
-
-
The method
qiskit.providers.ibmq.experimentservice.ExperimentService.experiments()
now acceptshub
,group
, andproject
as filtering keywords. -
Methods
qiskit.providers.ibmq.experiment.ExperimentService.experiments()
andqiskit.providers.ibmq.experiment.ExperimentService.analysis_results()
now support alimit
parameter that allows you to limit the number of experiments and analysis results returned. -
The method
qiskit.providers.ibmq.experimentservice.ExperimentService.experiments()
now acceptsexclude_mine
andmine_only
as filtering keywords. -
The method
qiskit.providers.ibmq.experimentservice.ExperimentService.experiments()
now acceptsexclude_public
andpublic_only
as filtering keywords. -
qiskit.providers.ibmq.managed.IBMQJobManager.run()
now accepts a singleQuantumCircuit
orSchedule
in addition to a list of them. -
The
least_busy()
function now skips backends that are operational but paused, meaning they are accepting but not processing jobs. -
You can now pickle an
IBMQJob
instance, as long as it doesn't contain custom data that is not picklable (e.g. in Qobj header). -
You can now use the two new methods,
qiskit.providers.ibmq.AccountProvider.services()
andqiskit.providers.ibmq.AccountProvider.service()
to find out what services are available to your account and get an instance of a particular service. -
The
qiskit.providers.ibmq.IBMQBackend.reservations()
method now always returns the reservation scheduling modes even for reservations that you don't own.
Upgrade Notes¶
-
A number of previously deprecated methods and features have been removed, including:
-
qiskit.providers.ibmq.job.IBMQJob.to_dict()
-
qiskit.providers.ibmq.job.IBMQJob.from_dict()
-
Qconfig.py support
-
Use of proxy URLs that do not include protocols
-
-
A new parameter,
limit
is now the first parameter for bothqiskit.providers.ibmq.experiment.ExperimentService.experiments()
andqiskit.providers.ibmq.experiment.ExperimentService.analysis_results()
methods. Thislimit
has a default value of 10, meaning by deafult only 10 experiments and analysis results will be returned. -
IBM Quantum credentials are now loaded only from sections of the
qiskitrc
file that start with 'ibmq'. This allows theqiskitrc
file to be used for other functionality.
Bug Fixes¶
-
Fixes the issue wherein a job could be left in the
CREATING
state if job submit fails half-way through. -
Fixes the issue wherein using Jupyter backend widget would fail if the backend's basis gates do not include the traditional u1, u2, and u3. Fixes #844
-
Fixes the infinite loop raised when passing an
IBMQRandomService
instance to a child process. -
Fixes the issue wherein a
TypeError
is raised if the server returns an error code but the response data is not in the expected format.
Qiskit 0.23.6¶
Aer 0.7.5¶
Prelude¶
This release is a bugfix release that fixes compatibility in the precompiled binary wheel packages with numpy versions < 1.20.0. The previous release 0.7.4 was building the binaries in a way that would require numpy 1.20.0 which has been resolved now, so the precompiled binary wheel packages will work with any numpy compatible version.
IBM Q Provider 0.11.1¶
No change
Qiskit 0.23.5¶
Terra 0.16.4¶
Prelude¶
This release is a bugfix release that primarily fixes compatibility with numpy 1.20.0. This numpy release deprecated their local aliases for Python's numeric types ( np.int
-> int
, np.float
-> float
, etc.) and the usage of these aliases in Qiskit resulted in a large number of deprecation warnings being emitted. This release fixes this so you can run Qiskit with numpy 1.20.0 without those deprecation warnings.
Aer 0.7.4¶
Bug Fixes¶
Fixes compatibility with numpy 1.20.0. This numpy release deprecated their local aliases for Python's numeric types ( np.int
-> int
, np.float
-> float
, etc.) and the usage of these aliases in Qiskit Aer resulted in a large number of deprecation warnings being emitted. This release fixes this so you can run Qiskit Aer with numpy 1.20.0 without those deprecation warnings.
Ignis 0.5.2¶
Prelude¶
This release is a bugfix release that primarily fixes compatibility with numpy 1.20.0. It is also the first release to include support for Python 3.9. Earlier releases (including 0.5.0 and 0.5.1) worked with Python 3.9 but did not indicate this in the package metadata, and there was no upstream testing for those releases. This release fixes that and was tested on Python 3.9 (in addition to 3.6, 3.7, and 3.8).
Bug Fixes¶
-
networkx is explicitly listed as a dependency now. It previously was an implicit dependency as it was required for the
qiskit.ignis.verification.topological_codes
module but was not correctly listed as a depdendency as qiskit-terra also requires networkx and is also a depdency of ignis so it would always be installed in practice. However, it is necessary to list it as a requirement for future releases of qiskit-terra that will not require networkx. It's also important to correctly list the dependencies of ignis in case there were a future incompatibility between version requirements.
Aqua 0.8.2¶
IBM Q Provider 0.11.1¶
No change
Qiskit 0.23.4¶
Terra 0.16.3¶
Bug Fixes¶
-
Fixed an issue introduced in 0.16.2 that would cause errors when running
transpile()
on a circuit with a series of 1 qubit gates and a non-gate instruction that only operates on a qubit (e.g.Reset
). Fixes #5736
IBM Q Provider 0.11.1¶
No change
Qiskit 0.23.3¶
Terra 0.16.2¶
New Features¶
-
Python 3.9 support has been added in this release. You can now run Qiskit Terra using Python 3.9.
Upgrade Notes¶
-
The class
MCXGrayCode
will now create aC3XGate
ifnum_ctrl_qubits
is 3 and aC4XGate
ifnum_ctrl_qubits
is 4. This is in addition to the previous functionality where for any of the modes of the :class:'qiskit.library.standard_gates.x.MCXGate`, ifnum_ctrl_bits
is 1, aCXGate
is created, and if 2, aCCXGate
is created.
Bug Fixes¶
-
Pulse
Delay
instructions are now explicitly assembled asPulseQobjInstruction
objects included in thePulseQobj
output fromassemble()
.Previously, we could ignore
Delay
instructions in aSchedule
as part ofassemble()
as the time was explicit in thePulseQobj
objects. But, now with pulse gates, there are situations where we can schedule ONLY a delay, and not including the delay itself would remove the delay. -
Circuits with custom gate calibrations can now be scheduled with the transpiler without explicitly providing the durations of each circuit calibration.
-
The
BasisTranslator
andUnroller
passes, in some cases, had not been preserving the global phase of the circuit under transpilation. This has been fixed. -
A bug in
qiskit.pulse.builder.frequency_offset()
where whencompensate_phase
was set a factor of \(2\pi\) was missing from the appended phase. -
Fix the global phase of the output of the
QuantumCircuit
methodrepeat()
. If a circuit with global phase is appended to another circuit, the global phase is currently not propagated. Simulators rely on this, since the phase otherwise gets applied multiple times. This sets the global phase ofrepeat()
to 0 before appending the repeated circuit instead of multiplying the existing phase times the number of repetitions. -
Fixes bug in
SparsePauliOp
where multiplying by a certain non Python builtin Numpy scalar types returned incorrect values. Fixes #5408 -
The definition of the Hellinger fidelity from has been corrected from the previous defition of \(1-H(P,Q)\) to \([1-H(P,Q)^2]^2\) so that it is equal to the quantum state fidelity of P, Q as diagonal density matrices.
-
Reduce the number of CX gates in the decomposition of the 3-controlled X gate,
C3XGate
. Compiled and optimized in the U CX basis, now only 14 CX and 16 U gates are used instead of 20 and 22, respectively. -
Fixes the issue wherein using Jupyter backend widget or
qiskit.tools.backend_monitor()
would fail if the backend's basis gates do not include the traditional u1, u2, and u3. -
When running
qiskit.compiler.transpile()
on a list of circuits with a single element, the function used to return a circuit instead of a list. Now, whenqiskit.compiler.transpile()
is called with a list, it will return a list even if that list has a single element. See #5260.from qiskit import * qc = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc . measure_all () transpiled = transpile ([ qc ]) print ( type ( transpiled ), len ( transpiled ))
Aer 0.7.3¶
New Features¶
-
Python 3.9 support has been added in this release. You can now run Qiskit Aer using Python 3.9 without building from source.
Bug Fixes¶
-
Fixes issue with setting
QasmSimulator
basis gates when using"method"
and"noise_model"
options together, and when using them with a simulator constructed usingfrom_backend()
. Now the listed basis gates will be the intersection of gates supported by the backend configuration, simulation method, and noise model basis gates. If the intersection of the noise model basis gates and simulator basis gates is empty a warning will be logged. -
Fixes a bug that resulted in c_if not working when the width of the conditional register was greater than 64. See #1077.
-
Fixes bug in
from_backend()
andfrom_backend()
wherebasis_gates
was set incorrectly for IBMQ devices with basis gate set['id', 'rz', 'sx', 'x', 'cx']
. Now the noise model will always have the same basis gates as the backend basis gates regardless of whether those instructions have errors in the noise model or not. -
Fixes a bug when applying truncation in the matrix product state method of the QasmSimulator.
IBM Q Provider 0.11.1¶
No change
Qiskit 0.23.2¶
Aer 0.7.2¶
New Features¶
-
Add the CMake flag
DISABLE_CONAN
(default=``OFF``)s. When installing from source, setting this toON
allows bypassing the Conan package manager to find libraries that are already installed on your system. This is also available as an environment variableDISABLE_CONAN
, which takes precedence over the CMake flag. This is not the official procedure to build AER. Thus, the user is responsible of providing all needed libraries and corresponding files to make them findable to CMake.
Bug Fixes¶
-
Fixes a bug with nested OpenMP flag was being set to true when it shouldn't be.
IBM Q Provider 0.11.1¶
No change
Qiskit 0.23.1¶
Terra 0.16.1¶
Bug Fixes¶
-
Fixed an issue where an error was thrown in execute for valid circuits built with delays.
-
The QASM definition of 'c4x' in qelib1.inc has been corrected to match the standard library definition for C4XGate.
-
Fixes a bug in subtraction for quantum channels \(A - B\) where \(B\) was an
Operator
object. Negation was being applied to the matrix in the Operator representation which is not equivalent to negation in the quantum channel representation. -
Changes the way
_evolve_instruction()
access qubits to handle the case of an instruction with multiple registers.
Aer 0.7.1¶
Upgrade Notes¶
-
The minimum cmake version to build qiskit-aer has increased from 3.6 to 3.8. This change was necessary to enable fixing GPU version builds that support running on x86_64 CPUs lacking AVX2 instructions.
Bug Fixes¶
-
qiskit-aer with GPU support will now work on systems with x86_64 CPUs lacking AVX2 instructions. Previously, the GPU package would only run if the AVX2 instructions were available. Fixes #1023
-
Fixes bug with
AerProvider
where options set on the returned backends usingset_options()
were stored in the provider and would persist for subsequent calls toget_backend()
for the same named backend. Now every call to andbackends()
returns a new instance of the simulator backend that can be configured. -
Fixes bug in the error message returned when a circuit contains unsupported simulator instructions. Previously some supported instructions were also being listed in the error message along with the unsupported instructions.
-
Fix bug where the "sx"` gate
SXGate
was not listed as a supported gate in the C++ code, in StateOpSet of matrix_product_state.hp. -
Fix bug where
"csx"
,"cu2"
,"cu3"
were incorrectly listed as supported basis gates for the"density_matrix"
method of theQasmSimulator
. -
In MPS, apply_kraus was operating directly on the input bits in the parameter qubits, instead of on the internal qubits. In the MPS algorithm, the qubits are constantly moving around so all operations should be applied to the internal qubits.
-
When invoking MPS::sample_measure, we need to first sort the qubits to the default ordering because this is the assumption in qasm_controller.This is done by invoking the method move_all_qubits_to_sorted_ordering. It was correct in sample_measure_using_apply_measure, but missing in sample_measure_using_probabilities.
Ignis 0.5.1¶
Bug Fixes¶
-
Fix the
"auto"
method of theTomographyFitter
,StateTomographyFitter
, andProcessTomographyFitter
to only use"cvx"
if CVXPY is installed and a third-party SDP solver other than SCS is available. This is because the SCS solver has lower accuracy than other solver methods and often returns a density matrix or Choi-matrix that is not completely-positive and fails validation when used with theqiskit.quantum_info.state_fidelity()
orqiskit.quantum_info.process_fidelity()
functions.
Aqua 0.8.1¶
0.8.1¶
New Features¶
-
A new algorithm has been added: the Born Openheimer Potential Energy surface for the calculation of potential energy surface along different degrees of freedom of the molecule. The algorithm is called
BOPESSampler
. It further provides functionalities of fitting the potential energy surface to an analytic function of predefined potentials.some details.
Critical Issues¶
-
Be aware that
initial_state
parameter inQAOA
has now different implementation as a result of a bug fix. The previous implementation wrongly mixed the user providedinitial_state
with Hadamard gates. The issue is fixed now. No attention needed if your code does not make use of the user providedinitial_state
parameter.
Bug Fixes¶
-
optimize_svm method of qp_solver would sometimes fail resulting in an error like this ValueError: cannot reshape array of size 1 into shape (200,1) This addresses the issue by adding an L2 norm parameter, lambda2, which defaults to 0.001 but can be changed via the QSVM algorithm, as needed, to facilitate convergence.
-
A method
one_letter_symbol
has been removed from theVarType
in the latest build of DOCplex making Aqua incompatible with this version. So instead of using this method an explicit type check of variable types has been introduced in the Aqua optimization module. -
:meth`~qiskit.aqua.operators.state_fns.DictStateFn.sample()` could only handle real amplitudes, but it is fixed to handle complex amplitudes. #1311 <https://github.com/Qiskit/qiskit-aqua/issues/1311> for more details.
-
Trotter class did not use the reps argument in constructor. #1317 <https://github.com/Qiskit/qiskit-aqua/issues/1317> for more details.
-
Raise an AquaError if :class`qiskit.aqua.operators.converters.CircuitSampler` samples an empty operator. #1321 <https://github.com/Qiskit/qiskit-aqua/issues/1321> for more details.
-
to_opflow()
returns a correct operator when coefficients are complex numbers. #1381 <https://github.com/Qiskit/qiskit-aqua/issues/1381> for more details. -
Let backend simulators validate NoiseModel support instead of restricting to Aer only in QuantumInstance.
-
Correctly handle PassManager on QuantumInstance
transpile
method by calling itsrun
method if it exists. -
A bug that mixes custom
initial_state
inQAOA
with Hadamard gates has been fixed. This doesn't change functionality of QAOA if no initial_state is provided by the user. Attention should be taken if your implementation uses QAOA with cusominitial_state
parameter as the optimization results might differ. -
Previously, setting seed_simulator=0 in the QuantumInstance did not set any seed. This was only affecting the value 0. This has been fixed.
IBM Q Provider 0.11.1¶
New Features¶
-
qiskit.providers.ibmq.experiment.Experiment
now has three additional attributes, hub, group, and project, that identify the provider used to create the experiment. -
Methods
qiskit.providers.ibmq.experiment.ExperimentService.experiments()
andqiskit.providers.ibmq.experiment.ExperimentService.analysis_results()
now support alimit
parameter that allows you to limit the number of experiments and analysis results returned.
Upgrade Notes¶
-
A new parameter,
limit
is now the first parameter for bothqiskit.providers.ibmq.experiment.ExperimentService.experiments()
andqiskit.providers.ibmq.experiment.ExperimentService.analysis_results()
methods. Thislimit
has a default value of 10, meaning by deafult only 10 experiments and analysis results will be returned.
Bug Fixes¶
-
Fixes the issue wherein a job could be left in the
CREATING
state if job submit fails half-way through. -
Fixes the infinite loop raised when passing an
IBMQRandomService
instance to a child process.
Qiskit 0.23.0¶
Terra 0.16.0¶
Prelude¶
The 0.16.0 release includes several new features and bug fixes. The major features in this release are the following:
-
Introduction of scheduled circuits, where delays can be used to control the timing and alignment of operations in the circuit.
-
Compilation of quantum circuits from classical functions, such as oracles.
-
Ability to compile and optimize single qubit rotations over different Euler basis as well as the phase + square-root(X) basis (i.e.
['p', 'sx']
), which will replace the older IBM Quantum basis of['u1', 'u2', 'u3']
. -
Tracking of
global_phase()
on theQuantumCircuit
class has been extended through thetranspiler
,quantum_info
, andassembler
modules, as well as the BasicAer and Aer simulators. Unitary and state vector simulations will now return global phase-correct unitary matrices and state vectors.
Also of particular importance for this release is that Python 3.5 is no longer supported. If you are using Qiskit Terra with Python 3.5, the 0.15.2 release is that last version which will work.
New Features¶
-
Global R gates have been added to
qiskit.circuit.library
. This includes the global R gate (GR
), global Rx (GRX
) and global Ry (GRY
) gates which are derived from theGR
gate, and global Rz (GRZ
) that is defined in a similar way to theGR
gates. The global R gates are defined on a number of qubits simultaneously, and act as a direct sum of R gates on each qubit.For example:
from qiskit import QuantumCircuit , QuantumRegister import numpy as np num_qubits = 3 qr = QuantumRegister ( num_qubits ) qc = QuantumCircuit ( qr ) qc . compose ( GR ( num_qubits , theta = np . pi / 3 , phi = 2 * np . pi / 3 ), inplace = True )
will create a
QuantumCircuit
on aQuantumRegister
of 3 qubits and perform aRGate
of an angle \(\theta = \frac{\pi}{3}\) about an axis in the xy-plane of the Bloch spheres that makes an angle of \(\phi = \frac{2\pi}{3}\) with the x-axis on each qubit. -
A new color scheme,
iqx
, has been added to thempl
backend for the circuit drawerqiskit.visualization.circuit_drawer()
andqiskit.circuit.QuantumCircuit.draw()
. This uses the same color scheme as the Circuit Composer on the IBM Quantum Experience website. There are now 3 available color schemes -default
,iqx
, andbw
.There are two ways to select a color scheme. The first is to use a user config file, by default in the
~/.qiskit
directory, in the filesettings.conf
under the[Default]
heading, a user can entercircuit_mpl_style = iqx
to select theiqx
color scheme.The second way is to add
{'name': 'iqx'}
to thestyle
kwarg to theQuantumCircuit.draw
method or to thecircuit_drawer
function. The second way will override the setting in the settings.conf file. For example:from qiskit.circuit import QuantumCircuit circuit = QuantumCircuit ( 2 ) circuit . h ( 0 ) circuit . cx ( 0 , 1 ) circuit . measure_all () circuit . draw ( 'mpl' , style = { 'name' : 'iqx' })
-
In the
style
kwarg for the the circuit drawerqiskit.visualization.circuit_drawer()
andqiskit.circuit.QuantumCircuit.draw()
thedisplaycolor
field with thempl
backend now allows for entering both the gate color and the text color for each gate type in the form(gate_color, text_color)
. This allows the use of light and dark gate colors with contrasting text colors. Users can still set only the gate color, in which case thegatetextcolor
field will be used. Gate colors can be set in thestyle
dict for any number of gate types, from one to the entiredisplaycolor
dict. For example:from qiskit.circuit import QuantumCircuit circuit = QuantumCircuit ( 1 ) circuit . h ( 0 ) style_dict = { 'displaycolor' : { 'h' : ( '#FA74A6' , '#000000' )}} circuit . draw ( 'mpl' , style = style_dict )
or
style_dict = { 'displaycolor' : { 'h' : '#FA74A6' }} circuit . draw ( 'mpl' , style = style_dict )
-
Two alignment contexts are added to the pulse builder (
qiskit.pulse.builder
) to facilitate writing a repeated pulse sequence with delays.-
qiskit.pulse.builder.align_equispaced()
inserts delays with equivalent length in between pulse schedules within the context. -
qiskit.pulse.builder.align_func()
offers more advanced control of pulse position. This context takes a callable that calculates a fractional coordinate of i-th pulse and aligns pulses within the context. This makes coding of dynamical decoupling easy.
-
-
A
rep_delay
parameter has been added to theQasmQobj
class under the run configuration,QasmQobjConfig
. This parameter is used to denote the time between program executions. It must be chosen from the backend range given by theBackendConfiguration
methodrep_delay_range()
. If a value is not provided a backend default,qiskit.providers.models.BackendConfiguration.default_rep_delay
, will be used.rep_delay
will only work on backends which allow for dynamic repetition time. This is can be checked with theBackendConfiguration
propertydynamic_reprate_enabled
. -
The
qobj_schema.json
JSON Schema file inqiskit.schemas
has been updated to include therep_delay
as an optional configuration property for QASM Qobjs. -
The
backend_configuration_schema.json
JSON Schema file inqiskit.schemas
has been updated to includedynamic_reprate_enabled
,rep_delay_range
anddefault_rep_delay
as optional properties for a QASM backend configuration payload. -
A new optimization pass,
qiskit.transpiler.passes.TemplateOptimization
has been added to the transpiler. This pass applies a template matching algorithm described in arXiv:1909.05270 that replaces all compatible maximal matches in the circuit.To implement this new transpiler pass a new module,
template_circuits
, was added to the circuit library (qiskit.circuit.library
). This new module contains all the Toffoli circuit templates used in theTemplateOptimization
.This new pass is not currently included in the preset pass managers (
qiskit.transpiler.preset_passmanagers
), to use it you will need to create a customPassManager
. -
A new version of the providers interface has been added. This new interface, which can be found in
qiskit.providers
, provides a new versioning mechanism that will enable changes to the interface to happen in a compatible manner over time. The new interface should be simple to migrate existing providers, as it is mostly identical except for the explicit versioning.Besides having explicitly versioned abstract classes the key changes for the new interface are that the
BackendV1
methodrun()
can now take aQuantumCircuit
orSchedule
object as inputs instead ofQobj
objects. To go along with that options are now part of a backend class so that users can configure run time options when running with a circuit. The final change is thatqiskit.providers.JobV1
can now be synchronous or asynchronous, the exact configuration and method for configuring this is up to the provider, but there are interface hook points to make it explicit which execution model a job is running under in theJobV1
abstract class. -
A new kwarg,
inplace
, has been added to the functionqiskit.result.marginal_counts()
. This kwarg is used to control whether the contents are marginalized in place or a new copy is returned, forResult
object input. This parameter does not have any effect for an inputdict
orCounts
object. -
An initial version of a classical function compiler,
qiskit.circuit.classicalfunction
, has been added. This enables compiling typed python functions (operating only on bits of typeInt1
at the moment) intoQuantumCircuit
objects. For example:from qiskit.circuit import classical_function , Int1 @classical_function def grover_oracle ( a : Int1 , b : Int1 , c : Int1 , d : Int1 ) -> Int1 : x = not a and b y = d and not c z = not x or y return z quantum_circuit = grover_oracle . synth () quantum_circuit . draw ()
q_0: ──■────o────■─────────■─────── │ │ │ │ q_1: ──o────┼────┼────■────o────■── │ │ │ │ │ │ q_2: ──┼────┼────o────■────■────┼── │ │ │ │ │ │ q_3: ──o────┼────■────■────■────o── ┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐ q_4: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├ └───┘└───┘└───┘└───┘└───┘└───┘
The parameter
registerless=False
in theqiskit.circuit.classicalfunction.ClassicalFunction
methodsynth()
creates a circuit with registers refering to the parameter names. For example:quantum_circuit = grover_oracle . synth ( registerless = False ) quantum_circuit . draw ()
d: ──■────o────■─────────■─────── │ │ │ │ c: ──o────┼────┼────■────o────■── │ │ │ │ │ │ b: ──┼────┼────o────■────■────┼── │ │ │ │ │ │ a: ──o────┼────■────■────■────o── ┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐ return: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├ └───┘└───┘└───┘└───┘└───┘└───┘
A decorated classical function can be used the same way as any other quantum gate when appending it to a circuit.
circuit = QuantumCircuit ( 5 ) circuit . append ( grover_oracle , range ( 5 )) circuit . draw ()
┌────────────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 ├ │ │ q_2: ┤2 Grover_oracle ├ │ │ q_3: ┤3 ├ │ │ q_4: ┤4 ├ └────────────────┘
The
GROVER_ORACLE
gate is synthesized when its decomposition is required.circuit . decompose () . draw ()
q_0: ──■────o────■─────────■─────── │ │ │ │ q_1: ──o────┼────┼────■────o────■── │ │ │ │ │ │ q_2: ──┼────┼────o────■────■────┼── │ │ │ │ │ │ q_3: ──o────┼────■────■────■────o── ┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐ q_4: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├ └───┘└───┘└───┘└───┘└───┘└───┘
The feature requires
tweedledum
, a library for synthesizing quantum circuits, that can be installed via pip withpip install tweedledum
. -
A new class
qiskit.circuit.Delay
for representing a delay instruction in a circuit has been added. A new methoddelay()
is now available for easily appending delays to circuits. This makes it possible to describe timing-sensitive experiments (e.g. T1/T2 experiment) in the circuit level.from qiskit import QuantumCircuit qc = QuantumCircuit ( 1 , 1 ) qc . delay ( 500 , 0 , unit = 'ns' ) qc . measure ( 0 , 0 ) qc . draw ()
┌────────────────┐┌─┐ q: ┤ Delay(500[ns]) ├┤M├ └────────────────┘└╥┘ c: 1/═══════════════════╩═ 0
-
A new argument
scheduling_method
forqiskit.compiler.transpile()
has been added. It is required when transpiling circuits with delays. Ifscheduling_method
is specified, the transpiler returns a scheduled circuit such that all idle times in it are padded with delays (i.e. start time of each instruction is uniquely determined). This makes it possible to see how scheduled instructions (gates) look in the circuit level.from qiskit import QuantumCircuit , transpile from qiskit.test.mock.backends import FakeAthens qc = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) scheduled_circuit = transpile ( qc , backend = FakeAthens (), scheduling_method = "alap" ) print ( "Duration in dt:" , scheduled_circuit . duration ) scheduled_circuit . draw ( idle_wires = False )
┌─────────┐ ┌────┐┌─────────┐ q_0 -> 0 ───┤ Rz(π/2) ├────┤ √X ├┤ Rz(π/2) ├──■── ┌──┴─────────┴───┐└────┘└─────────┘┌─┴─┐ q_1 -> 1 ┤ Delay(160[dt]) ├─────────────────┤ X ├ └────────────────┘ └───┘
See also
timeline_drawer()
for the best visualization of scheduled circuits. -
A new fuction
qiskit.compiler.sequence()
has been also added so that we can convert a scheduled circuit into aSchedule
to make it executable on a pulse-enabled backend.from qiskit.compiler import sequence sched = sequence ( scheduled_circuit , pulse_enabled_backend )
-
The
schedule()
has been updated so that it can schedule circuits with delays. Now there are two paths to schedule a circuit with delay:qc = QuantumCircuit ( 1 , 1 ) qc . h ( 0 ) qc . delay ( 500 , 0 , unit = 'ns' ) qc . h ( 0 ) qc . measure ( 0 , 0 ) sched_path1 = schedule ( qc . decompose (), backend ) sched_path2 = sequence ( transpile ( qc , backend , scheduling_method = 'alap' ), backend ) assert pad ( sched_path1 ) == sched_path2
Refer to the release notes and documentation for
transpile()
andsequence()
for the details on the other path. -
Added the
GroverOperator
to the circuit library (qiskit.circuit.library
) to construct the Grover operator used in Grover's search algorithm and Quantum Amplitude Amplification/Estimation. Provided with an oracle in form of a circuit,GroverOperator
creates the textbook Grover operator. To generalize this for amplitude amplification and use a generic operator instead of Hadamard gates as state preparation, thestate_in
argument can be used. -
The
InstructionScheduleMap
methodsget()
andpop()
methods now takeParameterExpression
instances in addition to numerical values for schedule generator parameters. If the generator is a function, expressions may be bound before or within the function call. If the generator is aParametrizedSchedule
, expressions must be bound before the schedule itself is bound/called. -
A new class
LinearAmplitudeFunction
was added to the circuit library (qiskit.circuit.library
) for mapping (piecewise) linear functions on qubit amplitudes,\[F|x\rangle |0\rangle = \sqrt{1 - f(x)}|x\rangle |0\rangle + \sqrt{f(x)}|x\rangle |1\rangle\]
The mapping is based on a controlled Pauli Y-rotations and a Taylor approximation, as described in https://arxiv.org/abs/1806.06893. This circuit can be used to compute expectation values of linear functions using the quantum amplitude estimation algorithm.
-
The new jupyter magic
monospaced_output
has been added to theqiskit.tools.jupyter
module. This magic sets the Jupyter notebook output font to "Courier New", when possible. When used this fonts returns text circuit drawings that are better aligned.import qiskit.tools.jupyter % monospaced_output
-
A new transpiler pass,
Optimize1qGatesDecomposition
, has been added. This transpiler pass is an alternative to the existingOptimize1qGates
that uses theOneQubitEulerDecomposer
class to decompose and simplify a chain of single qubit gates. This method is compatible with any basis set, whileOptimize1qGates
only works for u1, u2, and u3. The default pass managers foroptimization_level
1, 2, and 3 have been updated to use this new pass if the basis set doesn't include u1, u2, or u3. -
The
OneQubitEulerDecomposer
now supports two new basis,'PSX'
and'U'
. These can be specified with thebasis
kwarg on the constructor. This will decompose the matrix into a circuit usingPGate
andSXGate
for'PSX'
, andUGate
for'U'
. -
A new method
remove()
has been added to theqiskit.transpiler.PassManager
class. This method enables removing a pass from aPassManager
instance. It works on indexes, similar toreplace()
. For example, to remove theRemoveResetInZeroState
pass from the pass manager used at optimization level 1:from qiskit.transpiler.preset_passmanagers import level_1_pass_manager from qiskit.transpiler.passmanager_config import PassManagerConfig pm = level_1_pass_manager ( PassManagerConfig ()) pm . draw ()
[ 0 ] FlowLinear : UnrollCustomDefinitions , BasisTranslator [ 1 ] FlowLinear : RemoveResetInZeroState [ 2 ] DoWhile : Depth , FixedPoint , Optimize1qGates , CXCancellation
The stage
[1]
withRemoveResetInZeroState
can be removed like this:pass_manager . remove ( 1 ) pass_manager . draw ()
[ 0 ] FlowLinear : UnrollCustomDefinitions , BasisTranslator [ 1 ] DoWhile : Depth , FixedPoint , Optimize1qGates , CXCancellation
-
Several classes to load probability distributions into qubit amplitudes;
UniformDistribution
,NormalDistribution
, andLogNormalDistribution
were added to the circuit library (qiskit.circuit.library
). The normal and log-normal distribution support both univariate and multivariate distributions. These circuits are central to applications in finance where quantum amplitude estimation is used. -
Support for pulse gates has been added to the
QuantumCircuit
class. This enables aQuantumCircuit
to override (for basis gates) or specify (for standard and custom gates) a definition of aGate
operation in terms of time-ordered signals across hardware channels. In other words, it enables the option to provide pulse-level custom gate calibrations.The circuits are built exactly as before. For example:
from qiskit import pulse from qiskit.circuit import QuantumCircuit , Gate class RxGate ( Gate ): def __init__ ( self , theta ): super () . __init__ ( 'rxtheta' , 1 , [ theta ]) circ = QuantumCircuit ( 1 ) circ . h ( 0 ) circ . append ( RxGate ( 3.14 ), [ 0 ])
Then, the calibration for the gate can be registered using the
QuantumCircuit
methodadd_calibration()
which takes aSchedule
definition as well as the qubits and parameters that it is defined for:# Define the gate implementation as a schedule with pulse . build () as custom_h_schedule : pulse . play ( pulse . library . Drag ( ... ), pulse . DriveChannel ( 0 )) with pulse . build () as q1_x180 : pulse . play ( pulse . library . Gaussian ( ... ), pulse . DriveChannel ( 1 )) # Register the schedule to the gate circ . add_calibration ( 'h' , [ 0 ], custom_h_schedule ) # or gate.name string to register circ . add_calibration ( RxGate ( 3.14 ), [ 0 ], q1_x180 ) # Can accept gate
Previously, this functionality could only be used through complete Pulse Schedules. Additionally, circuits can now be submitted to backends with your custom definitions (dependent on backend support).
Circuits with pulse gates can still be lowered to a
Schedule
by using theschedule()
function.The calibrated gate can also be transpiled using the regular transpilation process:
transpiled_circuit = transpile ( circ , backend )
The transpiled circuit will leave the calibrated gates on the same qubit as the original circuit and will not unroll them to the basis gates.
-
Support for disassembly of
PulseQobj
objects has been added to theqiskit.assembler.disassemble()
function. For example:from qiskit import pulse from qiskit.assembler.disassemble import disassemble from qiskit.compiler.assemble import assemble from qiskit.test.mock import FakeOpenPulse2Q backend = FakeOpenPulse2Q () d0 = pulse . DriveChannel ( 0 ) d1 = pulse . DriveChannel ( 1 ) with pulse . build ( backend ) as sched : with pulse . align_right (): pulse . play ( pulse . library . Constant ( 10 , 1.0 ), d0 ) pulse . shift_phase ( 3.11 , d0 ) pulse . measure_all () qobj = assemble ( sched , backend = backend , shots = 512 ) scheds , run_config , header = disassemble ( qobj )
-
A new kwarg,
coord_type
has been added toqiskit.visualization.plot_bloch_vector()
. This kwarg enables changing the coordinate system used for the input parameter that describes the positioning of the vector on the Bloch sphere in the generated visualization. There are 2 supported values for this new kwarg,'cartesian'
(the default value) and'spherical'
. If thecoord_type
kwarg is set to'spherical'
the list of parameters taken in are of the form[r, theta, phi]
wherer
is the radius,theta
is the inclination from +z direction, andphi
is the azimuth from +x direction. For example:from numpy import pi from qiskit.visualization import plot_bloch_vector x = 0 y = 0 z = 1 r = 1 theta = pi phi = 0 # Cartesian coordinates, where (x,y,z) are cartesian coordinates # for bloch vector plot_bloch_vector ([ x , y , z ])
plot_bloch_vector ([ x , y , z ], coord_type = "cartesian" ) # Same as line above
# Spherical coordinates, where (r,theta,phi) are spherical coordinates # for bloch vector plot_bloch_vector ([ r , theta , phi ], coord_type = "spherical" )
-
Pulse
Schedule
objects now support usingParameterExpression
objects for parameters.For example:
from qiskit.circuit import Parameter from qiskit import pulse alpha = Parameter ( '⍺' ) phi = Parameter ( 'ϕ' ) qubit = Parameter ( 'q' ) amp = Parameter ( 'amp' ) schedule = pulse . Schedule () schedule += SetFrequency ( alpha , DriveChannel ( qubit )) schedule += ShiftPhase ( phi , DriveChannel ( qubit )) schedule += Play ( Gaussian ( duration = 128 , sigma = 4 , amp = amp ), DriveChannel ( qubit )) schedule += ShiftPhase ( - phi , DriveChannel ( qubit ))
Parameter assignment is done via the
assign_parameters()
method:schedule . assign_parameters ({ alpha : 4.5e9 , phi : 1.57 , qubit : 0 , amp : 0.2 })
Expressions and partial assignment also work, such as:
beta = Parameter ( 'b' ) schedule += SetFrequency ( alpha + beta , DriveChannel ( 0 )) schedule . assign_parameters ({ alpha : 4.5e9 }) schedule . assign_parameters ({ beta : phi / 6.28 })
-
A new visualization function
timeline_drawer()
was added to theqiskit.visualization
module.For example:
from qiskit.visualization import timeline_drawer from qiskit import QuantumCircuit , transpile from qiskit.test.mock import FakeAthens qc = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) timeline_drawer ( transpile ( qc , FakeAthens (), scheduling_method = 'alap' ))
Upgrade Notes¶
-
Type checking for the
params
kwarg of the constructor for theGate
class and its subclasses has been changed. Previously allGate
parameters had to be in a set of allowed types defined in theInstruction
class. Now a new method,validate_parameter()
is used to determine if a parameter type is valid or not. The definition of this method in a subclass will take priority over its parent. For example,UnitaryGate
accepts a parameter of the typenumpy.ndarray
and defines a customvalidate_parameter()
method that returns the parameter if it's annumpy.ndarray
. This takes priority over the function defined in its parent classGate
. IfUnitaryGate
were to be used as parent for a new class, thisvalidate_parameter
method would be used unless the new child class defines its own method. -
The previously deprecated methods, arguments, and properties named
n_qubits
andnumberofqubits
have been removed. These were deprecated in the 0.13.0 release. The full set of changes are:Class
Old
New
QuantumCircuit
n_qubits
num_qubits
Pauli
numberofqubits
num_qubits
Function
Old Argument
New Argument
qiskit.circuit.random.random_circuit()
n_qubits
num_qubits
qiskit.circuit.library.MSGate
n_qubits
num_qubits
-
Inserting a parameterized
Gate
instance into aQuantumCircuit
now creates a copy of that gate which is used in the circuit. If changes are made to the instance inserted into the circuit it will no longer be reflected in the gate in the circuit. This change was made to fix an issue when inserting a single parameterizedGate
object into multiple circuits. -
The function
qiskit.result.marginal_counts()
now, by default, does not modify theqiskit.result.Result
instance parameter. Previously, theResult
object was always modified in place. A new kwarginplace
has been addedmarginal_counts()
which enables using the previous behavior wheninplace=True
is set. -
The
U3Gate
definition has been changed to be in terms of theUGate
class. TheUGate
class has no definition. It is therefore not possible to unroll every circuit in terms of U3 and CX anymore. Instead, U and CX can be used for every circuit. -
The deprecated support for running Qiskit Terra with Python 3.5 has been removed. To use Qiskit Terra from this release onward you will now need to use at least Python 3.6. If you are using Python 3.5 the last version which will work is Qiskit Terra 0.15.2.
-
In the
PulseBackendConfiguration
in thehamiltonian
attributes thevars
field is now returned in a unit of Hz instead of the previously used GHz. This change was made to be consistent with the units used with the other attributes in the class. -
The previously deprecated support for passing in a dictionary as the first positional argument to
DAGNode
constructor has been removed. Using a dictonary for the first positional argument was deprecated in the 0.13.0 release. To create aDAGNode
object now you should directly pass the attributes as kwargs on the constructor. -
The keyword arguments for the circuit gate methods (for example:
qiskit.circuit.QuantumCircuit.cx
)q
,ctl*
, andtgt*
, which were deprecated in the 0.12.0 release, have been removed. Instead, onlyqubit
,control_qubit*
andtarget_qubit*
can be used as named arguments for these methods. -
The previously deprecated module
qiskit.extensions.standard
has been removed. This module has been deprecated since the 0.14.0 release. Theqiskit.circuit.library
can be used instead. Additionally, all the gate classes previously inqiskit.extensions.standard
are still importable fromqiskit.extensions
. -
The previously deprecated gates in the module
qiskit.extensions.quantum_initializer
:DiagGate
, UCG`,UCPauliRotGate
,UCRot
,UCRXGate
,UCX
,UCRYGate
,UCY
,UCRZGate
,UCZ
have been removed. These were all deprecated in the 0.14.0 release and have alternatives available in the circuit library (qiskit.circuit.library
). -
The previously deprecated
qiskit.circuit.QuantumCircuit
gate methodiden()
has been removed. This was deprecated in the 0.13.0 release andi()
orid()
can be used instead.
Deprecation Notes¶
-
The use of a
numpy.ndarray
for a parameter in theparams
kwarg for the constructor of theGate
class and subclasses has been deprecated and will be removed in future releases. This was done as part of the refactoring of howparms
type checking is handled for theGate
class. If you have a custom gate class which is a subclass ofGate
directly (or via a different parent in the hierarchy) that accepts anndarray
parameter, you should define a customvalidate_parameter()
method for your class that will return the allowed parameter type. For example:def validate_parameter ( self , parameter ): """Custom gate parameter has to be an ndarray.""" if isinstance ( parameter , numpy . ndarray ): return parameter else : raise CircuitError ( "invalid param type {0} in gate " " {1} " . format ( type ( parameter ), self . name ))
-
The
num_ancilla_qubits
property of thePiecewiseLinearPauliRotations
andPolynomialPauliRotations
classes has been deprecated and will be removed in a future release. Instead the propertynum_ancillas
should be used instead. This was done to make it consistent with theQuantumCircuit
methodnum_ancillas()
. -
The
qiskit.circuit.library.MSGate
class has been deprecated, but will remain in place to allow loading of old jobs. It has been replaced with theqiskit.circuit.library.GMS
class which should be used instead. -
The
MSBasisDecomposer
transpiler pass has been deprecated and will be removed in a future release. Theqiskit.transpiler.passes.BasisTranslator
pass can be used instead. -
The
QuantumCircuit
methodsu1
,u2
andu3
are now deprecated. Instead the following replacements can be used.u1 ( theta ) = p ( theta ) = u ( 0 , 0 , theta ) u2 ( phi , lam ) = u ( pi / 2 , phi , lam ) = p ( pi / 2 + phi ) sx p ( pi / 2 lam ) u3 ( theta , phi , lam ) = u ( theta , phi , lam ) = p ( phi + pi ) sx p ( theta + pi ) sx p ( lam )
The gate classes themselves,
U1Gate
,U2Gate
andU3Gate
remain, to allow loading of old jobs.
Bug Fixes¶
-
The
Result
class's methodsdata()
,get_memory()
,get_counts()
,get_unitary()
, andget_statevector ` will now emit a warning when the ``experiment`()
kwarg is specified for attempting to fetch results using either aQuantumCircuit
orSchedule
instance, when more than one entry matching the instance name is present in theResult
object. Note that only the first entry matching this name will be returned. Fixes #3207 -
The
qiskit.circuit.QuantumCircuit
methodappend()
can now be used to insert one parameterized gate instance into multiple circuits. This fixes a previous issue where inserting a single parameterizedGate
object into multiple circuits would cause failures when one circuit had a parameter assigned. Fixes #4697 -
Previously the
qiskit.execute.execute()
function would incorrectly disallow both thebackend
andpass_manager
kwargs to be specified at the same time. This has been fixed so that bothbackend
andpass_manager
can be used together on calls toexecute()
. Fixes #5037 -
The
QuantumCircuit
methodunitary()
method has been fixed to accept a single integer for theqarg
argument (when adding a 1-qubit unitary). The allowed types for theqargs
argument are nowint
,Qubit
, or a list of integers. Fixes #4944 -
Previously, calling
inverse()
on aBlueprintCircuit
object could fail if its internal data property was not yet populated. This has been fixed so that the callinginverse()
will populate the internal data before generating the inverse of the circuit. Fixes #5140 -
Fixed an issue when creating a
qiskit.result.Counts
object from an empty data dictionary. Now this will create an emptyCounts
object. Themost_frequent()
method is also updated to raise a more descriptive exception when the object is empty. Fixes #5017 -
Fixes a bug where setting
ctrl_state
of aUnitaryGate
would be applied twice; once in the creation of the matrix for the controlled unitary and again when calling thedefinition()
method of theqiskit.circuit.ControlledGate
class. This would give the appearence that settingctrl_state
had no effect. -
Previously the
ControlledGate
methodinverse()
would not preserve thectrl_state
parameter in some cases. This has been fixed so that callinginverse()
will preserve the valuectrl_state
in its output. -
Fixed a bug in the
mpl
output backend of the circuit drawerqiskit.circuit.QuantumCircuit.draw()
andqiskit.visualization.circuit_drawer()
that would cause the drawer to fail if thestyle
kwarg was set to a string. The correct behavior would be to treat that string as a path to a JSON file containing the style sheet for the visualization. This has been fixed, and warnings are raised if the JSON file for the style sheet can't be loaded. -
Fixed an error where loading a QASM file via
from_qasm_file()
orfrom_qasm_str()
would fail if au
,phase(p)
,sx
, orsxdg
gate were present in the QASM file. Fixes #5156 -
Fixed a bug that would potentially cause registers to be mismapped when unrolling/decomposing a gate defined with only one 2-qubit operation.
Aer 0.7.0¶
Prelude¶
This 0.7.0 release includes numerous performance improvements and significant enhancements to the simulator interface, and drops support for Python 3.5. The main interface changes are configurable simulator backends, and constructing preconfigured simulators from IBMQ backends. Noise model an basis gate support has also been extended for most of the Qiskit circuit library standard gates, including new support for 1 and 2-qubit rotation gates. Performance improvements include adding SIMD support to the density matrix and unitary simulation methods, reducing the used memory and improving the performance of circuits using statevector and density matrix snapshots, and adding support for Kraus instructions to the gate fusion circuit optimization for greatly improving the performance of noisy statevector simulations.
New Features¶
-
Adds basis gate support for the
qiskit.circuit.Delay
instruction to theStatevectorSimulator
,UnitarySimulator
, andQasmSimulator
. Note that this gate is treated as an identity gate during simulation and the delay length parameter is ignored. -
Adds basis gate support for the single-qubit gate
qiskit.circuit.library.UGate
to theStatevectorSimulator
,UnitarySimulator
, and the"statevector"
,"density_matrix"
,"matrix_product_state"
, and"extended_stabilizer"
methods of theQasmSimulator
. -
Adds basis gate support for the phase gate
qiskit.circuit.library.PhaseGate
to theStatevectorSimulator
,StatevectorSimulator
,UnitarySimulator
, and the"statevector"
,"density_matrix"
,"matrix_product_state"
, and"extended_stabilizer"
methods of theQasmSimulator
. -
Adds basis gate support for the controlled-phase gate
qiskit.circuit.library.CPhaseGate
to theStatevectorSimulator
,StatevectorSimulator
,UnitarySimulator
, and the"statevector"
,"density_matrix"
, and"matrix_product_state"
methods of theQasmSimulator
. -
Adds support for the multi-controlled phase gate
qiskit.circuit.library.MCPhaseGate
to theStatevectorSimulator
,UnitarySimulator
, and the"statevector"
method of theQasmSimulator
. -
Adds support for the \(\sqrt(X)\) gate
qiskit.circuit.library.SXGate
to theStatevectorSimulator
,UnitarySimulator
, andQasmSimulator
. -
Adds support for 1 and 2-qubit Qiskit circuit library rotation gates
RXGate
,RYGate
,RZGate
,RGate
,RXXGate
,RYYGate
,RZZGate
,RZXGate
to theStatevectorSimulator
,UnitarySimulator
, and the"statevector"
and"density_matrix"
methods of theQasmSimulator
. -
Adds support for multi-controlled rotation gates
"mcr"
,"mcrx"
,"mcry"
,"mcrz"
to theStatevectorSimulator
,UnitarySimulator
, and the"statevector"
method of theQasmSimulator
. -
Make simulator backends configurable. This allows setting persistant options such as simulation method and noise model for each simulator backend object.
The
QasmSimulator
andPulseSimulator
can also be configured from anIBMQBackend
backend object using the :meth:`~qiskit.providers.aer.QasmSimulator.from_backend method. For theQasmSimulator
this will configure the coupling map, basis gates, and basic device noise model based on the backend configuration and properties. For thePulseSimulator
the system model and defaults will be configured automatically from the backend configuration, properties and defaults.For example a noisy density matrix simulator backend can be constructed as
QasmSimulator(method='density_matrix', noise_model=noise_model)
, or an ideal matrix product state simulator asQasmSimulator(method='matrix_product_state')
.A benefit is that a
PulseSimulator
instance configured from a backend better serves as a drop-in replacement to the original backend, making it easier to swap in and out a simulator and real backend, e.g. when testing code on a simulator before using a real backend. For example, in the following code-block, thePulseSimulator
is instantiated from theFakeArmonk()
backend. All configuration and default data is copied into the simulator instance, and so when it is passed as an argument toassemble
, it behaves as if the original backend was supplied (e.g. defaults fromFakeArmonk
will be present and used byassemble
).armonk_sim = qiskit . providers . aer . PulseSimulator . from_backend ( FakeArmonk ()) pulse_qobj = assemble ( schedules , backend = armonk_sim ) armonk_sim . run ( pulse_qobj )
While the above example is small, the demonstrated 'drop-in replacement' behavior should greatly improve the usability in more complicated work-flows, e.g. when calibration experiments are constructed using backend attributes.
-
Adds support for qobj global phase to the
StatevectorSimulator
,UnitarySimulator
, and statevector methods of theQasmSimulator
. -
Improves general noisy statevector simulation performance by adding a Kraus method to the gate fusion circuit optimization that allows applying gate fusion to noisy statevector simulations with general Kraus noise.
-
Use move semantics for statevector and density matrix snapshots for the "statevector" and "density_matrix" methods of the
QasmSimulator
if they are the final instruction in a circuit. This reduces the memory usage of the simulator improves the performance by avoiding copying a large array in the results. -
Adds support for general Kraus
QauntumError
gate errors in theNoiseModel
to the"matrix_product_state"
method of theQasmSimulator
. -
Adds support for density matrix snapshot instruction
qiskit.providers.aer.extensions.SnapshotDensityMatrix
to the"matrix_product_state"
method of theQasmSimulator
. -
Extends the SIMD vectorization of the statevector simulation method to the unitary matrix, superoperator matrix, and density matrix simulation methods. This gives roughtly a 2x performance increase general simulation using the
UnitarySimulator
, the"density_matrix"
method of theQasmSimulator
, gate fusion, and noise simulation. -
Adds a custom vector class to C++ code that has better integration with Pybind11. This haves the memory requirement of the
StatevectorSimulator
by avoiding an memory copy during Python binding of the final simulator state.
Upgrade Notes¶
-
AER now uses Lapack to perform some matrix related computations. It uses the Lapack library bundled with OpenBlas (already available in Linux and Macos typical OpenBlas dsitributions; Windows version distributed with AER) or with the accelerate framework in MacOS.
-
The deprecated support for running qiskit-aer with Python 3.5 has been removed. To use qiskit-aer >=0.7.0 you will now need at least Python 3.6. If you are using Python 3.5 the last version which will work is qiskit-aer 0.6.x.
-
Updates gate fusion default thresholds so that gate fusion will be applied to circuits with of more than 14 qubits for statevector simulations on the
StatevectorSimulator
andQasmSimulator
.For the
"density_matrix"
method of theQasmSimulator
and for theUnitarySimulator
gate fusion will be applied to circuits with more than 7 qubits.Custom qubit threshold values can be set using the
fusion_threshold
backend option iebackend.set_options(fusion_threshold=10)
-
Changes
fusion_threshold
backend option to apply fusion when the number of qubits is above the threshold, not equal or above the threshold, to match the behavior of the OpenMP qubit threshold parameter.
Deprecation Notes¶
-
qiskit.providers.aer.noise.NoiseModel.set_x90_single_qubit_gates()
has been deprecated as unrolling to custom basis gates has been added to the qiskit transpiler. The correct way to use an X90 based noise model is to define noise on the Sqrt(X)"sx"
or"rx"
gate and one of the single-qubit phase gates"u1"
,"rx"
, or"p"
in the noise model. -
The
variance
kwarg of Snapshot instructions has been deprecated. This function computed the sample variance in the snapshot due to noise model sampling, not the variance due to measurement statistics so was often being used incorrectly. If noise modeling variance is required single shot snapshots should be used so variance can be computed manually in post-processing.
Bug Fixes¶
-
Fixes bug in the
StatevectorSimulator
that caused it to always run as CPU with double-precision without SIMD/AVX2 support even on systems with AVX2, or when single-precision or the GPU method was specified in the backend options. -
Fixes some for-loops in C++ code that were iterating over copies rather than references of container elements.
-
Fixes a bug where snapshot data was always copied from C++ to Python rather than moved where possible. This will halve memory usage and improve simulation time when using large statevector or density matrix snapshots.
-
Fix State::snapshot_pauli_expval to return correct Y expectation value in stabilizer simulator. Refer to #895 <https://github.com/Qiskit/qiskit-aer/issues/895> for more details.
-
The controller_execute wrappers have been adjusted to be functors (objects) rather than free functions. Among other things, this allows them to be used in multiprocessing.pool.map calls.
-
Add missing available memory checks for the
StatevectorSimulator
andUnitarySimulator
. This throws an exception if the memory required to simulate the number of qubits in a circuit exceeds the available memory of the system.
Ignis 0.5.0¶
Prelude¶
This release includes a new module for expectation value measurement error mitigation, improved plotting functionality for quantum volume experiments, several bug fixes, and drops support for Python 3.5.
New Features¶
-
The
qiskit.ignis.verification.randomized_benchmarking.randomized_benchmarking_seq()
function allows an optional input of gate objects as interleaved_elem. In addition, the CNOT-Dihedral classqiskit.ignis.verification.randomized_benchmarking.CNOTDihedral
has a new method to_instruction, and the existing from_circuit method has an optional input of an Instruction (in addition to QuantumCircuit). -
The
qiskit.ignis.verification.randomized_benchmarking.CNOTDihedral
now contains the following new features. Initialization from various types of objects: CNOTDihedral, ScalarOp, QuantumCircuit, Instruction and Pauli. Converting to a matrix using to_matrix and to an operator using to_operator. Tensor product methods tensor and expand. Calculation of the adjoint, conjugate and transpose using conjugate, adjoint and transpose methods. Verify that an element is CNOTDihedral using is_cnotdihedral method. Decomposition method to_circuit of a CNOTDihedral element into a circuit was extended to allow any number of qubits, based on the function decompose_cnotdihedral_general. -
Adds expectation value measurement error mitigation to the mitigation module. This supports using complete N-qubit assignment matrix, single-qubit tensored assignment matrix, or continuous time Markov process (CTMP) [1] measurement error mitigation when computing expectation values of diagonal operators from counts dictionaries. Expectation values are computed using the using the
qiskit.ignis.mitigation.expectation_value()
function.Calibration circuits for calibrating a measurement error mitigator are generated using the
qiskit.ignis.mitigation.expval_meas_mitigator_circuits()
function, and the result fitted using theqiskit.ignis.mitigation.ExpvalMeasMitigatorFitter
class. The fitter returns a mitigator object can the be supplied as an argument to theexpectation_value()
function to apply mitigation.- [1] S Bravyi, S Sheldon, A Kandala, DC Mckay, JM Gambetta,
-
Mitigating measurement errors in multi-qubit experiments, arXiv:2006.14044 [quant-ph].
Example:
The following example shows calibrating a 5-qubit expectation value measurement error mitigator using the
'tensored'
method.from qiskit import execute from qiskit.test.mock import FakeVigo import qiskit.ignis.mitigation as mit backend = FakeVigo () num_qubits = backend . configuration () . num_qubits # Generate calibration circuits circuits , metadata = mit . expval_meas_mitigator_circuits ( num_qubits , method = 'tensored' ) result = execute ( circuits , backend , shots = 8192 ) . result () # Fit mitigator mitigator = mit . ExpvalMeasMitigatorFitter ( result , metadata ) . fit () # Plot fitted N-qubit assignment matrix mitigator . plot_assignment_matrix ()
<AxesSubplot:xlabel='Prepared State', ylabel='Measured State'>
The following shows how to use the above mitigator to apply measurement error mitigation to expectation value computations
from qiskit import QuantumCircuit # Test Circuit with expectation value -1. qc = QuantumCircuit ( num_qubits ) qc . x ( range ( num_qubits )) qc . measure_all () # Execute shots = 8192 seed_simulator = 1999 result = execute ( qc , backend , shots = 8192 , seed_simulator = 1999 ) . result () counts = result . get_counts ( 0 ) # Expectation value of Z^N without mitigation expval_nomit , error_nomit = mit . expectation_value ( counts ) print ( 'Expval (no mitigation): {:.2f} \u00B1 {:.2f} ' . format ( expval_nomit , error_nomit )) # Expectation value of Z^N with mitigation expval_mit , error_mit = mit . expectation_value ( counts , meas_mitigator = mitigator ) print ( 'Expval (with mitigation): {:.2f} \u00B1 {:.2f} ' . format ( expval_mit , error_mit ))
Expval (no mitigation): -0.66 ± 0.01 Expval (with mitigation): -0.99 ± 0.01
-
Adds Numba as an optional dependency. Numba is used to significantly increase the performance of the
qiskit.ignis.mitigation.CTMPExpvalMeasMitigator
class used for expectation value measurement error mitigation with the CTMP method. -
Add two methods to
qiskit.ignis.verification.quantum_volume.QVFitter
.-
qiskit.ignis.verification.quantum_volume.QVFitter.calc_z_value()
to calculate z value in standard normal distribution using mean and standard deviation sigma. If sigma = 0, it raises a warning and assigns a small value (1e-10) for sigma so that the code still runs. -
qiskit.ignis.verification.quantum_volume.QVFitter.calc_confidence_level()
to calculate confidence level using z value.
-
-
Store confidence level even when hmean < 2/3 in
qiskit.ignis.verification.quantum_volume.QVFitter.qv_success()
. -
Add explanations for how to calculate statistics based on binomial distribution in
qiskit.ignis.verification.quantum_volume.QVFitter.calc_statistics()
. -
The
qiskit.ignis.verification.QVFitter
methodplot_qv_data()
has been updated to return amatplotlib.Figure
object. Previously, it would not return anything. By returning a figure this makes it easier to integrate the visualizations into a largermatplotlib
workflow. -
The error bars in the figure produced by the
qiskit.ignis.verification.QVFitter
methodqiskit.ignis.verification.QVFitter.plot_qv_data()
has been updated to represent two-sigma confidence intervals. Previously, the error bars represent one-sigma confidence intervals. The success criteria of Quantum Volume benchmarking requires heavy output probability > 2/3 with one-sided two-sigma confidence (~97.7%). Changing error bars to represent two-sigma confidence intervals allows easily identification of success in the figure. -
A new kwarg,
figsize
has been added to theqiskit.ignis.verification.QVFitter
methodqiskit.ignis.verification.QVFitter.plot_qv_data()
. This kwarg takes in a tuple of the form(x, y)
wherex
andy
are the dimension in inches to make the generated plot. -
The
qiskit.ignis.verification.quantum_volume.QVFitter.plot_hop_accumulative()
method has been added to plot heavy output probability (HOP) vs number of trials similar to Figure 2a of Quantum Volume 64 paper (arXiv:2008.08571). HOP of individual trials are plotted as scatters and cummulative HOP are plotted in red line. Two-sigma confidence intervals are plotted as shaded area and 2/3 success threshold is plotted as dashed line. -
The
qiskit.ignis.verification.quantum_volume.QVFitter.plot_qv_trial()
method has been added to plot individual trials, leveraging on theqiskit.visualization.plot_histogram()
method from Qiskit Terra. Bitstring counts are plotted as overlapping histograms for ideal (hollow) and experimental (filled) values. Experimental heavy output probability are shown on the legend. Median probability is plotted as red dashed line.
Upgrade Notes¶
-
The deprecated support for running qiskit-ignis with Python 3.5 has been removed. To use qiskit-ignis >=0.5.0 you will now need at least Python 3.6. If you are using Python 3.5 the last version which will work is qiskit-ignis 0.4.x.
Bug Fixes¶
-
Fixing a bug in the class
qiskit.ignis.verification.randomized_benchmarking.CNOTDihedral
for elements with more than 5 quits. -
Fix the confidence level threshold for
qiskit.ignis.verification.quantum_volume.QVFitter.qv_success()
to 0.977 corresponding to z = 2 as defined by the QV paper Algorithm 1. -
Fix a bug at
qiskit.ignis.verification.randomized_benchmarking.randomized_benchmarking_seq()
which caused all the subsystems with the same size in the given rb_pattern to have the same gates when a 'rand_seed' parameter was given to the function.
Aqua 0.8.0¶
Prelude¶
This release introduces an interface for running the available methods for Bosonic problems. In particular we introduced a full interface for running vibronic structure calculations.
This release introduces an interface for excited states calculations. It is now easier for the user to create a general excited states calculation. This calculation is based on a Driver which provides the relevant information about the molecule, a Transformation which provides the information about the mapping of the problem into a qubit Hamiltonian, and finally a Solver. The Solver is the specific way which the excited states calculation is done (the algorithm). This structure follows the one of the ground state calculations. The results are modified to take lists of expectation values instead of a single one. The QEOM and NumpyEigensolver are adapted to the new structure. A factory is introduced to run a numpy eigensolver with a specific filter (to target states of specific symmetries).
VQE expectation computation with Aer qasm_simulator now defaults to a computation that has the expected shot noise behavior.
New Features¶
-
Introduced an option warm_start that should be used when tuning other options does not help. When this option is enabled, a relaxed problem (all variables are continuous) is solved first and the solution is used to initialize the state of the optimizer before it starts the iterative process in the solve method.
-
The amplitude estimation algorithms now use
QuantumCircuit
objects as inputs to specify the A- and Q operators. This change goes along with the introduction of theGroverOperator
in the circuit library, which allows an intuitive and fast construction of different Q operators. For example, a Bernoulli-experiment can now be constructed asimport numpy as np from qiskit import QuantumCircuit from qiskit.aqua.algorithms import AmplitudeEstimation probability = 0.5 angle = 2 * np . sqrt ( np . arcsin ( probability )) a_operator = QuantumCircuit ( 1 ) a_operator . ry ( angle , 0 ) # construct directly q_operator = QuantumCircuit ( 1 ) q_operator . ry ( 2 * angle , 0 ) # construct via Grover operator from qiskit.circuit.library import GroverOperator oracle = QuantumCircuit ( 1 ) oracle . z ( 0 ) # good state = the qubit is in state |1> q_operator = GroverOperator ( oracle , state_preparation = a_operator ) # use default construction in QAE q_operator = None ae = AmplitudeEstimation ( a_operator , q_operator )
-
Add the possibility to compute Conditional Value at Risk (CVaR) expectation values.
Given a diagonal observable H, often corresponding to the objective function of an optimization problem, we are often not as interested in minimizing the average energy of our observed measurements. In this context, we are satisfied if at least some of our measurements achieve low energy. (Note that this is emphatically not the case for chemistry problems).
To this end, one might consider using the best observed sample as a cost function during variational optimization. The issue here, is that this can result in a non-smooth optimization surface. To resolve this issue, we can smooth the optimization surface by using not just the best observed sample, but instead average over some fraction of best observed samples. This is exactly what the CVaR estimator accomplishes [1].
Let \(\alpha\) be a real number in \([0,1]\) which specifies the fraction of best observed samples which are used to compute the objective function. Observe that if \(\alpha = 1\), CVaR is equivalent to a standard expectation value. Similarly, if \(\alpha = 0\), then CVaR corresponds to using the best observed sample. Intermediate values of \(\alpha\) interpolate between these two objective functions.
The functionality to use CVaR is included into the operator flow through a new subclass of OperatorStateFn called CVaRMeasurement. This new StateFn object is instantied in the same way as an OperatorMeasurement with the exception that it also accepts an alpha parameter and that it automatically enforces the is_measurement attribute to be True. Observe that it is unclear what a CVaRStateFn would represent were it not a measurement.
Examples:
qc = QuantumCircuit ( 1 ) qc . h ( 0 ) op = CVaRMeasurement ( Z , alpha = 0.5 ) @ CircuitStateFn ( primitive = qc , coeff = 1.0 ) result = op . eval ()
Similarly, an operator corresponding to a standard expectation value can be converted into a CVaR expectation using the CVaRExpectation converter.
Examples:
qc = QuantumCircuit ( 1 ) qc . h ( 0 ) op = ~ StateFn ( Z ) @ CircuitStateFn ( primitive = qc , coeff = 1.0 ) cvar_expecation = CVaRExpectation ( alpha = 0.1 ) . convert ( op ) result = cvar_expecation . eval ()
See [1] for additional details regarding this technique and it's empircal performance.
References:
- [1]: Barkoutsos, P. K., Nannicini, G., Robert, A., Tavernelli, I., and Woerner, S.,
-
"Improving Variational Quantum Optimization using CVaR" arXiv:1907.04769
-
New interface
Eigensolver
for Eigensolver algorithms. -
An interface for excited states calculation has been added to the chemistry module. It is now easier for the user to create a general excited states calculation. This calculation is based on a
Driver
which provides the relevant information about the molecule, aTransformation
which provides the information about the mapping of the problem into a qubit Hamiltonian, and finally a Solver. The Solver is the specific way which the excited states calculation is done (the algorithm). This structure follows the one of the ground state calculations. The results are modified to take lists of expectation values instead of a single one. TheQEOM
andNumpyEigensolver
are adapted to the new structure. A factory is introduced to run a numpy eigensolver with a specific filter (to target states of specific symmetries). -
In addition to the workflows for solving Fermionic problems, interfaces for calculating Bosonic ground and excited states have been added. In particular we introduced a full interface for running vibronic structure calculations.
-
The
OrbitalOptimizationVQE
has been added as new ground state solver in the chemistry module. This solver allows for the simulatneous optimization of the variational parameters and the orbitals of the molecule. The algorithm is introduced in Sokolov et al., The Journal of Chemical Physics 152 (12). -
A new algorithm has been added: the Born Openheimer Potential Energy surface for the calculation of potential energy surface along different degrees of freedom of the molecule. The algorithm is called
BOPESSampler
. It further provides functionalities of fitting the potential energy surface to an analytic function of predefined potentials. -
A feasibility check of the obtained solution has been added to all optimizers in the optimization stack. This has been implemented by adding two new methods to
QuadraticProgram
: *get_feasibility_info(self, x: Union[List[float], np.ndarray])
accepts an array and returns whether this solution is feasible and a list of violated variables(violated bounds) and a list of violated constraints. *is_feasible(self, x: Union[List[float], np.ndarray])
accepts an array and returns whether this solution is feasible or not. -
Add circuit-based versions of
FixedIncomeExpectedValue
,EuropeanCallDelta
,GaussianConditionalIndependenceModel
andEuropeanCallExpectedValue
toqiskit.finance.applications
. -
Gradient Framework.
qiskit.operators.gradients
Given an operator that represents either a quantum state resp. an expectation value, the gradient framework enables the evaluation of gradients, natural gradients, Hessians, as well as the Quantum Fisher Information.Suppose a parameterized quantum state |ψ(θ)〉 = V(θ)|ψ〉 with input state |ψ〉 and parametrized Ansatz V(θ), and an Operator O(ω).
Gradients: We want to compute \(d⟨ψ(θ)|O(ω)|ψ(θ)〉/ dω\) resp. \(d⟨ψ(θ)|O(ω)|ψ(θ)〉/ dθ\) resp. \(d⟨ψ(θ)|i〉⟨i|ψ(θ)〉/ dθ\).
The last case corresponds to the gradient w.r.t. the sampling probabilities of |ψ(θ). These gradients can be computed with different methods, i.e. a parameter shift, a linear combination of unitaries and a finite difference method.
Examples:
x = Parameter ( 'x' ) ham = x * X a = Parameter ( 'a' ) q = QuantumRegister ( 1 ) qc = QuantumCircuit ( q ) qc . h ( q ) qc . p ( params [ 0 ], q [ 0 ]) op = ~ StateFn ( ham ) @ CircuitStateFn ( primitive = qc , coeff = 1. ) value_dict = { x : 0.1 , a : np . pi / 4 } ham_grad = Gradient ( grad_method = 'param_shift' ) . convert ( operator = op , params = [ x ]) ham_grad . assign_parameters ( value_dict ) . eval () state_grad = Gradient ( grad_method = 'lin_comb' ) . convert ( operator = op , params = [ a ]) state_grad . assign_parameters ( value_dict ) . eval () prob_grad = Gradient ( grad_method = 'fin_diff' ) . convert ( operator = CircuitStateFn ( primitive = qc , coeff = 1. ), params = [ a ]) prob_grad . assign_parameters ( value_dict ) . eval ()
Hessians: We want to compute \(d^2⟨ψ(θ)|O(ω)|ψ(θ)〉/ dω^2\) resp. \(d^2⟨ψ(θ)|O(ω)|ψ(θ)〉/ dθ^2\) resp. \(d^2⟨ψ(θ)|O(ω)|ψ(θ)〉/ dθdω\) resp. \(d^2⟨ψ(θ)|i〉⟨i|ψ(θ)〉/ dθ^2\).
The last case corresponds to the Hessian w.r.t. the sampling probabilities of |ψ(θ). Just as the first order gradients, the Hessians can be evaluated with different methods, i.e. a parameter shift, a linear combination of unitaries and a finite difference method. Given a tuple of parameters
Hessian().convert(op, param_tuple)
returns the value for the second order derivative. If a list of parameters is givenHessian().convert(op, param_list)
returns the full Hessian for all the given parameters according to the given parameter order.QFI: The Quantum Fisher Information QFI is a metric tensor which is representative for the representation capacity of a parameterized quantum state |ψ(θ)〉 = V(θ)|ψ〉 generated by an input state |ψ〉 and a parametrized Ansatz V(θ). The entries of the QFI for a pure state read \([QFI]kl= Re[〈∂kψ|∂lψ〉−〈∂kψ|ψ〉〈ψ|∂lψ〉] * 4\).
Just as for the previous derivative types, the QFI can be computed using different methods: a full representation based on a linear combination of unitaries implementation, a block-diagonal and a diagonal representation based on an overlap method.
Examples:
q = QuantumRegister ( 1 ) qc = QuantumCircuit ( q ) qc . h ( q ) qc . p ( params [ 0 ], q [ 0 ]) op = ~ StateFn ( ham ) @ CircuitStateFn ( primitive = qc , coeff = 1. ) value_dict = { x : 0.1 , a : np . pi / 4 } qfi = QFI ( 'lin_comb_full' ) . convert ( operator = CircuitStateFn ( primitive = qc , coeff = 1. ), params = [ a ]) qfi . assign_parameters ( value_dict ) . eval ()
The combination of the QFI and the gradient lead to a special form of a gradient, namely
NaturalGradients: The natural gradient is a special gradient method which rescales a gradient w.r.t. a state parameter with the inverse of the corresponding Quantum Fisher Information (QFI) \(QFI^-1 d⟨ψ(θ)|O(ω)|ψ(θ)〉/ dθ\). Hereby, we can choose a gradient as well as a QFI method and a regularization method which is used together with a least square solver instead of exact invertion of the QFI:
Examples:
op = ~ StateFn ( ham ) @ CircuitStateFn ( primitive = qc , coeff = 1. ) nat_grad = NaturalGradient ( grad_method = 'lin_comb, qfi_method=' lin_comb_full ', \ regularization=' ridge ').convert(operator=op, params=params)
The gradient framework is also compatible with the optimizers from qiskit.aqua.components.optimizers. The derivative classes come with a gradient_wrapper() function which returns the corresponding callable.
-
Introduces
transformations
for the fermionic and bosonic transformation of a problem instance. Transforms the fermionic operator to qubit operator. Respective class for the transformation isfermionic_transformation
Introduces in algorithmsground_state_solvers
for the calculation of ground state properties. The calculation can be done either using anMinimumEigensolver
or usingAdaptVQE
Introduceschemistry/results
where the eigenstate_result and the electronic_structure_result are also used for the algorithms. Introduces Minimum Eigensolver factoriesminimum_eigensolver_factories
where chemistry specific minimum eigensolvers can be initialized Introduces orbital optimization vqeoovqe
as a ground state solver for chemistry applications -
New Algorithm result classes:
Grover
method_run()
returns classGroverResult
.AmplitudeEstimation
method_run()
returns classAmplitudeEstimationResult
.IterativeAmplitudeEstimation
method_run()
returns classIterativeAmplitudeEstimationResult
.MaximumLikelihoodAmplitudeEstimation
method_run()
returns classMaximumLikelihoodAmplitudeEstimationResult
.All new result classes are backwards compatible with previous result dictionary.
-
New Linear Solver result classes:
HHL
method_run()
returns classHHLResult
.NumPyLSsolver
method_run()
returns classNumPyLSsolverResult
.All new result classes are backwards compatible with previous result dictionary.
-
MinimumEigenOptimizationResult
now exposes properties:samples
andeigensolver_result
. The latter is obtained from the underlying algorithm used by the optimizer and specific to the algorithm.RecursiveMinimumEigenOptimizer
now returns an instance of the result classRecursiveMinimumEigenOptimizationResult
which in turn may contains intermediate results obtained from the underlying algorithms. The dedicated result class exposes propertiesreplacements
andhistory
that are specific to this optimizer. The depth of the history is managed by thehistory
parameter of the optimizer. -
GroverOptimizer
now returns an instance ofGroverOptimizationResult
and this result class exposes propertiesoperation_counts
,n_input_qubits
, andn_output_qubits
directly. These properties are not available in theraw_results
dictionary anymore. -
SlsqpOptimizer
now returns an instance ofSlsqpOptimizationResult
and this result class exposes additional properties specific to the SLSQP implementation. -
Support passing
QuantumCircuit
objects as generator circuits into theQuantumGenerator
. -
Removes the restriction to real input vectors in CircuitStateFn.from_vector. The method calls extensions.Initialize. The latter explicitly supports (in API and documentation) complex input vectors. So this restriction seems unnecessary.
-
Simplified AbelianGrouper using a graph coloring algorithm of retworkx. It is faster than the numpy-based coloring algorithm.
-
Allow calling
eval
on state function objects with no argument, which returns theVectorStateFn
representation of the state function. This is consistent behavior withOperatorBase.eval
, which returns theMatrixOp
representation, if no argument is passed. -
Adds
max_iterations
to theVQEAdapt
class in order to allow limiting the maximum number of iterations performed by the algorithm. -
VQE expectation computation with Aer qasm_simulator now defaults to a computation that has the expected shot noise behavior. The special Aer snapshot based computation, that is much faster, with the ideal output similar to state vector simulator, may still be chosen but like before Aqua 0.7 it now no longer defaults to this but can be chosen.
Upgrade Notes¶
-
Extension of the previous Analytic Quantum Gradient Descent (AQGD) classical optimizer with the AQGD with Epochs. Now AQGD performs the gradient descent optimization with a momentum term, analytic gradients, and an added customized step length schedule for parametrized quantum gates. Gradients are computed "analytically" using the quantum circuit when evaluating the objective function.
-
The deprecated support for running qiskit-aqua with Python 3.5 has been removed. To use qiskit-aqua >=0.8.0 you will now need at least Python 3.6. If you are using Python 3.5 the last version which will work is qiskit-aqua 0.7.x.
-
Added retworkx as a new dependency.
Deprecation Notes¶
-
The
i_objective
argument of the amplitude estimation algorithms has been renamed toobjective_qubits
. -
TransformationType
-
QubitMappingType
-
Deprecate the
CircuitFactory
and derived types. TheCircuitFactory
has been introduced as temporary class when theQuantumCircuit
missed some features necessary for applications in Aqua. Now that the circuit has all required functionality, the circuit factory can be removed. The replacements are shown in the following table.Circuit factory class | Replacement ------------------------------------+----------------------------------------------- CircuitFactory | use QuantumCircuit | UncertaintyModel | - UnivariateDistribution | - MultivariateDistribution | - NormalDistribution | qiskit.circuit.library.NormalDistribution MultivariateNormalDistribution | qiskit.circuit.library.NormalDistribution LogNormalDistribution | qiskit.circuit.library.LogNormalDistribution MultivariateLogNormalDistribution | qiskit.circuit.library.LogNormalDistribution UniformDistribution | qiskit.circuit.library.UniformDistribution MultivariateUniformDistribution | qiskit.circuit.library.UniformDistribution UnivariateVariationalDistribution | use parameterized QuantumCircuit MultivariateVariationalDistribution | use parameterized QuantumCircuit | UncertaintyProblem | - UnivariateProblem | - MultivariateProblem | - UnivariatePiecewiseLinearObjective | qiskit.circuit.library.LinearAmplitudeFunction
-
The ising convert classes
qiskit.optimization.converters.QuadraticProgramToIsing
andqiskit.optimization.converters.IsingToQuadraticProgram
have been deprecated and will be removed in a future release. Instead theqiskit.optimization.QuadraticProgram
methodsto_ising()
andfrom_ising()
should be used instead. -
Deprecate the
WeightedSumOperator
which has been ported to the circuit library asWeightedAdder
inqiskit.circuit.library
. -
Core Hamiltonian
class is deprecated in favor of theFermionicTransformation
Chemistry Operator
class is deprecated in favor of thetranformations
minimum_eigen_solvers/vqe_adapt
is also deprecated and moved as an implementation of the ground_state_solver interfaceapplications/molecular_ground_state_energy
is deprecated in favor ofground_state_solver
-
Optimizer.SupportLevel
nested enum is replaced byOptimizerSupportLevel
andOptimizer.SupportLevel
was removed. Use, for example,OptimizerSupportLevel.required
instead ofOptimizer.SupportLevel.required
. -
Deprecate the
UnivariateVariationalDistribution
andMultivariateVariationalDistribution
as input to theQuantumGenerator
. Instead, plainQuantumCircuit
objects can be used. -
Ignored fast and use_nx options of AbelianGrouper.group_subops to be removed in the future release.
-
GSLS optimizer class deprecated
__init__
parametermax_iter
in favor ofmaxiter
. SPSA optimizer class deprecated__init__
parametermax_trials
in favor ofmaxiter
. optimize_svm function deprecatedmax_iters
parameter in favor ofmaxiter
. ADMMParameters class deprecated__init__
parametermax_iter
in favor ofmaxiter
.
Bug Fixes¶
-
The UCCSD excitation list, comprising single and double excitations, was not being generated correctly when an active space was explicitly provided to UCSSD via the active_(un)occupied parameters.
-
For the amplitude estimation algorithms, we define the number of oracle queries as number of times the Q operator/Grover operator is applied. This includes the number of shots. That factor has been included in MLAE and IQAE but was missing in the 'standard' QAE.
-
Fix CircuitSampler.convert, so that the
is_measurement
property is propagated to converted StateFns. -
Fix double calculation of coefficients in :meth`~qiskit.aqua.operators.VectorStateFn.to_circuit_op`.
-
Calling PauliTrotterEvolution.convert on an operator including a term that is a scalar multiple of the identity gave an incorrect circuit, one that ignored the scalar coefficient. This fix includes the effect of the coefficient in the global_phase property of the circuit.
-
Make ListOp.num_qubits check that all ops in list have the same num_qubits Previously, the number of qubits in the first operator in the ListOp was returned. With this change, an additional check is made that all other operators also have the same number of qubits.
-
Make PauliOp.exp_i() generate the correct matrix with the following changes. 1) There was previously an error in the phase of a factor of 2. 2) The global phase was ignored when converting the circuit to a matrix. We now use qiskit.quantum_info.Operator, which is generally useful for converting a circuit to a unitary matrix, when possible.
-
Fixes the cyclicity detection as reported buggy in https://github.com/Qiskit/qiskit-aqua/issues/1184.
IBM Q Provider 0.11.0¶
Upgrade Notes¶
-
The deprecated support for running qiskit-ibmq-provider with Python 3.5 has been removed. To use qiskit-ibmq-provider >=0.11.0 you will now need at least Python 3.6. If you are using Python 3.5 the last version which will work is qiskit-ibmq-provider 0.10.x.
-
Prior to this release,
websockets
7.0 was used for Python 3.6. With this release,websockets
8.0 or above is required for all Python versions. The package requirements have been updated to reflect this.
Qiskit 0.22.0¶
IBM Q Provider 0.10.0¶
New Features¶
-
CQC randomness extractors can now be invoked asynchronously, using methods
run_async_ext1()
andrun_async_ext2()
. Each of these methods returns aCQCExtractorJob
instance that allows you to check on the job status (usingstatus()
) and wait for its result (usingblock_until_ready()
). Theqiskit.provider.ibmq.random.CQCExtractor.run()
method remains synchronous. -
You can now use the new IBMQ experiment service to query, retrieve, and download experiment related data. Interface to this service is located in the new
qiskit.providers.ibmq.experiment
package. Note that this feature is still in beta, and not all accounts have access to it. It is also subject to heavy modification in both functionality and API without backward compatibility. -
Two Jupyter magic functions, the IQX dashboard and the backend widget, are updated to display backend reservations. If a backend has reservations scheduled in the next 24 hours, time to the next one and its duration are displayed (e.g.
Reservation: in 6 hrs 30 min (60m)
). If there is a reservation and the backend is active, the backend status is displayed asactive [R]
.
Upgrade Notes¶
-
Starting from this release, the basis_gates returned by
qiskit.providers.ibmq.IBMQBackend.configuration()
may differ for each backend. You should update your program if it relies on the basis gates being['id','u1','u2','u3','cx']
. We recommend always using theconfiguration()
method to find backend configuration values instead of hard coding them. -
qiskit-ibmq-provider
release 0.10 requiresqiskit-terra
release 0.15 or above. The package metadata has been updated to reflect the new dependency.
Qiskit 0.21.0¶
IBM Q Provider 0.9.0¶
New Features¶
-
You can now access the IBMQ random number services, such as the CQC randomness extractor, using the new package
qiskit.providers.ibmq.random
. Note that this feature is still in beta, and not all accounts have access to it. It is also subject to heavy modification in both functionality and API without backward compatibility.
Bug Fixes¶
-
Fixes an issue that may raise a
ValueError
ifretrieve_job()
is used to retrieve a job submitted via the IBM Quantum Experience Composer. -
IBMQJobManager
has been updated so that if a time out happens while waiting for an old job to finish, the time out error doesn't prevent a new job to be submitted. Fixes #737
Qiskit 0.20.1¶
Terra 0.15.2¶
Bug Fixes¶
-
When accessing the
definition
attribute of a parameterizedGate
instance, the generatedQuantumCircuit
had been generated with an invalidParameterTable
, such that reading fromQuantumCircuit.parameters
or callingQuantumCircuit.bind_parameters
would incorrectly report the unbound parameters. This has been resolved. -
SXGate().inverse()
had previously returned an 'sx_dg' gate with a correctdefinition
but incorrectto_matrix
. This has been updated such thatSXGate().inverse()
returns anSXdgGate()
and vice versa. -
Instruction.inverse()
, when not overridden by a subclass, would in some cases return aGate
instance with an incorrectto_matrix
method. The instances of incorrectto_matrix
methods have been removed. -
For
C3XGate
with a non-zeroangle
, inverting the gate viaC3XGate.inverse()
had previously generated an incorrect inverse gate. This has been corrected. -
The
MCXGate
modes have been updated to return a gate of the same mode when calling.inverse()
. This resolves an issue where in some cases, transpiling a circuit containing the inverse of anMCXVChain
gate would raise an error. -
Previously, when creating a multiply controlled phase gate via
PhaseGate.control
, anMCU1Gate
gate had been returned. This has been had corrected so that anMCPhaseGate
is returned. -
Previously, attempting to decompose a circuit containing an
MCPhaseGate
would raise an error due to an inconsistency in the definition of theMCPhaseGate
. This has been corrected. -
QuantumCircuit.compose
andDAGCircuit.compose
had, in some cases, incorrectly translated conditional gates if the input circuit contained more than oneClassicalRegister
. This has been resolved. -
Fixed an issue when creating a
qiskit.result.Counts
object from an empty data dictionary. Now this will create an emptyCounts
object. Themost_frequent()
method is also updated to raise a more descriptive exception when the object is empty. Fixes #5017 -
Extending circuits with differing registers updated the
qregs
andcregs
properties accordingly, but not thequbits
andclbits
lists. As these are no longer generated from the registers but are cached lists, this lead to a discrepancy of registers and bits. This has been fixed and theextend
method explicitly updates the cached bit lists. -
Fix bugs of the concrete implementations of meth:~qiskit.circuit.ControlledGate.inverse method which do not preserve the
ctrl_state
parameter. -
A bug was fixed that caused long pulse schedules to throw a recursion error.
IBM Q Provider 0.8.0¶
No change
Qiskit 0.20.0¶
Terra 0.15.1¶
Prelude¶
The 0.15.0 release includes several new features and bug fixes. Some highlights for this release are:
This release includes the introduction of arbitrary basis translation to the transpiler. This includes support for directly targeting a broader range of device basis sets, e.g. backends implementing RZ, RY, RZ, CZ or iSwap gates.
The QuantumCircuit
class now tracks global phase. This means controlling a circuit which has global phase now correctly adds a relative phase, and gate matrix definitions are now exact rather than equal up to a global phase.
New Features¶
-
A new DAG class
qiskit.dagcircuit.DAGDependency
for representing the dependency form of circuit, In this DAG, the nodes are operations (gates, measure, barrier, etc…) and the edges corresponds to non-commutation between two operations. -
Four new functions are added to
qiskit.converters
for converting back and forth toDAGDependency
. These functions are:-
circuit_to_dagdependency()
to convert from aQuantumCircuit
object to aDAGDependency
object. -
dagdependency_to_circuit()
to convert from aDAGDependency
object to aQuantumCircuit
object. -
dag_to_dagdependency()
to convert from aDAGCircuit
object to aDAGDependency
object. -
dagdependency_to_dag()
to convert from aDAGDependency
object to aDAGCircuit
object.
For example:
from qiskit.converters.dagdependency_to_circuit import dagdependency_to_circuit from qiskit import QuantumRegister , ClassicalRegister , QuantumCircuit circuit_in = QuantumCircuit ( 2 ) circuit_in . h ( qr [ 0 ]) circuit_in . h ( qr [ 1 ]) dag_dependency = circuit_to_dagdependency ( circuit_in ) circuit_out = dagdepency_to_circuit ( dag_dependency )
-
-
Two new transpiler passes have been added to
qiskit.transpiler.passes
The first,UnrollCustomDefinitions
, unrolls all instructions in the circuit according to theirdefinition
property, stopping when reaching either the specifiedbasis_gates
or a set of gates in the providedEquivalenceLibrary
. The second,BasisTranslator
, uses the set of translations in the providedEquivalenceLibrary
to re-write circuit instructions in a specified basis. -
A new
translation_method
keyword argument has been added totranspile()
to allow selection of the method to be used for translating circuits to the available device gates. For example,transpile(circ, backend, translation_method='translator')
. Valid choices are:-
'unroller'
: to use theUnroller
pass -
'translator'
: to use theBasisTranslator
pass. -
'synthesis'
: to use theUnitarySynthesis
pass.
The default value is
'translator'
. -
-
A new class for handling counts result data,
qiskit.result.Counts
, has been added. This class is a subclass ofdict
and can be interacted with like any other dictionary. But, it includes helper methods and attributes for dealing with counts results from experiments and also handles post processing and formatting of binary strings at object initialization. ACounts
object can be created by passing a dictionary of counts with the keys being either integers, hexadecimal strings of the form'0x4a'
, binary strings of the form'0b1101'
, a bit string formatted across register and memory slots (ie'00 10'
), or a dit string. For example:from qiskit.result import Counts counts = Counts ({ "0x0': 1, '0x1', 3, '0x2': 1020})
-
A new method for constructing
qiskit.dagcircuit.DAGCircuit
objects has been added,from_networkx()
. This method takes in a networkxMultiDiGraph
object (in the format returned byto_networkx()
) and will return a newDAGCircuit
object. The intent behind this function is to enable transpiler pass authors to leverage networkx's graph algorithm library if a function is missing from the retworkx API. Although, hopefully in such casses an issue will be opened with retworkx issue tracker (or even better a pull request submitted). -
A new kwarg for
init_qubits
has been added toassemble()
andexecute()
. For backends that support this featureinit_qubits
can be used to control whether the backend executing the circuits inserts any initialization sequences at the start of each shot. By default this is set toTrue
meaning that all qubits can assumed to be in the ground state at the start of each shot. However, wheninit_qubits
is set toFalse
qubits will be uninitialized at the start of each experiment and between shots. Note, that the backend running the circuits has to support this feature for this flag to have any effect. -
A new kwarg
rep_delay
has been added toqiskit.compiler.assemble()
,qiskit.execute.execute()
, and the constructor forPulseQobjtConfig
.qiskit This new kwarg is used to denotes the time between program executions. It must be chosen from the list of valid values set as therep_delays
from a backend'sPulseBackendConfiguration
object which can be accessed asbackend.configuration().rep_delays
).The
rep_delay
kwarg will only work on backends which allow for dynamic repetition time. This will also be indicated in thePulseBackendConfiguration
object for a backend as thedynamic_reprate_enabled
attribute. Ifdynamic_reprate_enabled
isFalse
then therep_time
value specified forqiskit.compiler.assemble()
,qiskit.execute.execute()
, or the constructor forPulseQobjtConfig
will be used rather thanrep_delay
.rep_time
only allows users to specify the duration of a program, rather than the delay between programs. -
The
qobj_schema.json
JSON Schema file inqiskit.schemas
has been updated to include therep_delay
as an optional configuration property for pulse qobjs. -
The
backend_configuration_schema.json
JSON Schema file in mod:qiskit.schemas has been updated to includerep_delay_range
anddefault_rep_delay
as optional properties for a pulse backend configuration. -
A new attribute,
global_phase
, which is is used for tracking the global phase has been added to theqiskit.circuit.QuantumCircuit
class. For example:import math from qiskit import QuantumCircuit circ = QuantumCircuit ( 1 , global_phase = math . pi ) circ . u1 ( 0 )
The global phase may also be changed or queried with
circ.global_phase
in the above example. In either case the setting is in radians. If the circuit is converted to an instruction or gate the global phase is represented by two single qubit rotations on the first qubit.This allows for other methods and functions which consume a
QuantumCircuit
object to take global phase into account. For example. with theglobal_phase
attribute theto_matrix()
method for a gate can now exactly correspond to its decompositions instead of just up to a global phase.The same attribute has also been added to the
DAGCircuit
class so that global phase can be tracked when converting betweenQuantumCircuit
andDAGCircuit
. -
Two new classes,
AncillaRegister
andAncillaQubit
have been added to theqiskit.circuit
module. These are subclasses ofQuantumRegister
andQubit
respectively and enable marking qubits being ancillas. This will allow these qubits to be re-used in larger circuits and algorithms. -
A new method,
control()
, has been added to theQuantumCircuit
. This method will return a controlled version of theQuantumCircuit
object, with both open and closed controls. This functionality had previously only been accessible via theGate
class. -
A new method
repeat()
has been added to theQuantumCircuit
class. It returns a new circuit object containing a specified number of repetitions of the original circuit. For example:from qiskit.circuit import QuantumCircuit qc = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) repeated_qc = qc . repeat ( 3 ) repeated_qc . decompose () . draw ( output = 'mpl' )
The parameters are copied by reference, meaning that if you update the parameters in one instance of the circuit all repetitions will be updated.
-
A new method
reverse_bits()
has been added to theQuantumCircuit
class. This method will reverse the order of bits in a circuit (both quantum and classical bits). This can be used to switch a circuit from little-endian to big-endian and vice-versa. -
A new method,
combine_into_edge_map()
, was added to theqiskit.transpiler.Layout
class. This method enables converting converting twoLayout
objects into a qubit map for composing two circuits. -
A new class,
ConfigurableFakeBackend
, has been added to theqiskit.test.mock.utils
module. This new class enables the creation of configurable mock backends for use in testing. For example:from qiskit.test.mock.utils import ConfigurableFakeBackend backend = ConfigurableFakeBackend ( "Tashkent" , n_qubits = 100 , version = "0.0.1" , basis_gates = [ 'u1' ], qubit_t1 = 99. , qubit_t2 = 146. , qubit_frequency = 5. , qubit_readout_error = 0.01 , single_qubit_gates = [ 'u1' ])
will create a backend object with 100 qubits and all the other parameters specified in the constructor.
-
A new method
draw()
has been added to theqiskit.circuit.EquivalenceLibrary
class. This method can be used for drawing the contents of an equivalence library, which can be useful for debugging. For example:from numpy import pi from qiskit.circuit import EquivalenceLibrary from qiskit.circuit import QuantumCircuit from qiskit.circuit import QuantumRegister from qiskit.circuit import Parameter from qiskit.circuit.library import HGate from qiskit.circuit.library import U2Gate from qiskit.circuit.library import U3Gate my_equiv_library = EquivalenceLibrary () q = QuantumRegister ( 1 , 'q' ) def_h = QuantumCircuit ( q ) def_h . append ( U2Gate ( 0 , pi ), [ q [ 0 ]], []) my_equiv_library . add_equivalence ( HGate (), def_h ) theta = Parameter ( 'theta' ) phi = Parameter ( 'phi' ) lam = Parameter ( 'lam' ) def_u2 = QuantumCircuit ( q ) def_u2 . append ( U3Gate ( pi / 2 , phi , lam ), [ q [ 0 ]], []) my_equiv_library . add_equivalence ( U2Gate ( phi , lam ), def_u2 ) my_equiv_library . draw ()
-
A new Phase instruction,
SetPhase
, has been added toqiskit.pulse
. This instruction sets the phase of the subsequent pulses to the specified phase (in radians. For example:import numpy as np from qiskit.pulse import DriveChannel from qiskit.pulse import Schedule from qiskit.pulse import SetPhase sched = Schedule () sched += SetPhase ( np . pi , DriveChannel ( 0 ))
In this example, the phase of the pulses applied to
DriveChannel(0)
after theSetPhase
instruction will be set to \(\pi\) radians. -
A new pulse instruction
ShiftFrequency
has been added toqiskit.pulse.instructions
. This instruction enables shifting the frequency of a channel from its set frequency. For example:from qiskit.pulse import DriveChannel from qiskit.pulse import Schedule from qiskit.pulse import ShiftFrequency sched = Schedule () sched += ShiftFrequency ( - 340e6 , DriveChannel ( 0 ))
In this example all the pulses applied to
DriveChannel(0)
after theShiftFrequency
command will have the envelope a frequency decremented by 340MHz. -
A new method
conjugate()
has been added to theParameterExpression
class. This enables callingnumpy.conj()
without raising an error. Since aParameterExpression
object is real, it will return itself. This behaviour is analogous to Python floats/ints. -
A new class
PhaseEstimation
has been added toqiskit.circuit.library
. This circuit library class is the circuit used in the original formulation of the phase estimation algorithm in arXiv:quant-ph/9511026. Phase estimation is the task to to estimate the phase \(\phi\) of an eigenvalue \(e^{2\pi i\phi}\) of a unitary operator \(U\), provided with the corresponding eigenstate \(|psi\rangle\). That is\[U|\psi\rangle = e^{2\pi i\phi} |\psi\rangle\]
This estimation (and thereby this circuit) is a central routine to several well-known algorithms, such as Shor's algorithm or Quantum Amplitude Estimation.
-
The
qiskit.visualization
functionplot_state_qsphere()
has a new kwargshow_state_labels
which is used to control whether each blob in the qsphere visualization is labeled. By default this kwarg is set toTrue
and shows the basis states next to each blob by default. This feature can be disabled, reverting to the previous behavior, by setting theshow_state_labels
kwarg toFalse
. -
The
qiskit.visualization
functionplot_state_qsphere()
has a new kwargshow_state_phases
which is set toFalse
by default. When set toTrue
it displays the phase of each basis state. -
The
qiskit.visualization
functionplot_state_qsphere()
has a new kwarguse_degrees
which is set toFalse
by default. When set toTrue
it displays the phase of each basis state in degrees, along with the phase circle at the bottom right. -
A new class,
QuadraticForm
to theqiskit.circuit.library
module for implementing a a quadratic form on binary variables. The circuit library element implements the operation\[|x\rangle |0\rangle \mapsto |x\rangle |Q(x) \mod 2^m\rangle\]
for the quadratic form \(Q\) and \(m\) output qubits. The result is in the \(m\) output qubits is encoded in two's complement. If \(m\) is not specified, the circuit will choose the minimal number of qubits required to represent the result without applying a modulo operation. The quadratic form is specified using a matrix for the quadratic terms, a vector for the linear terms and a constant offset. If all terms are integers, the circuit implements the quadratic form exactly, otherwise it is only an approximation.
For example:
import numpy as np from qiskit.circuit.library import QuadraticForm A = np . array ([[ 1 , 2 ], [ - 1 , 0 ]]) b = np . array ([ 3 , - 3 ]) c = - 2 m = 4 quad_form_circuit = QuadraticForm ( m , A , b , c )
-
Add
qiskit.quantum_info.Statevector.expectation_value()
andqiskit.quantum_info.DensityMatrix.expectation_value()
methods for computing the expectation value of anqiskit.quantum_info.Operator
. -
For the
seed
kwarg in the constructor forqiskit.circuit.library.QuantumVolume
numpy random Generator objects can now be used. Previously, only integers were a valid input. This is useful when integratingQuantumVolume
as part of a larger function with its own random number generation, e.g. generating a sequence ofQuantumVolume
circuits. -
The
QuantumCircuit
methodcompose()
has a new kwargfront
which can be used for prepending the other circuit before the origin circuit instead of appending. For example:from qiskit.circuit import QuantumCircuit circ1 = QuantumCircuit ( 2 ) circ2 = QuantumCircuit ( 2 ) circ2 . h ( 0 ) circ1 . cx ( 0 , 1 ) circ1 . compose ( circ2 , front = True ) . draw ( output = 'mpl' )
-
Two new passes,
SabreLayout
andSabreSwap
for layout and routing have been added toqiskit.transpiler.passes
. These new passes are based on the algorithm presented in Li et al., "Tackling the Qubit Mapping Problem for NISQ-Era Quantum Devices", ASPLOS 2019. They can also be selected when using thetranspile()
function by setting thelayout_method
kwarg to'sabre'
and/or therouting_method
to'sabre'
to useSabreLayout
andSabreSwap
respectively. -
Added the method
replace()
to theqiskit.pulse.Schedule
class which allows a pulse instruction to be replaced with another. For example:from qiskit import pulse
d0 = pulse.DriveChannel(0)
sched = pulse.Schedule()
old = pulse.Play(pulse.Constant(100, 1.0), d0) new = pulse.Play(pulse.Constant(100, 0.1), d0)
sched += old
sched = sched.replace(old, new)
assert sched == pulse.Schedule(new)
-
Added new gate classes to
qiskit.circuit.library
for the \(\sqrt{X}\), its adjoint \(\sqrt{X}^\dagger\), and controlled \(\sqrt{X}\) gates asSXGate
,SXdgGate
, andCSXGate
. They can also be added to aQuantumCircuit
object using thesx()
,sxdg()
, andcsx()
respectively. -
Add support for
Reset
instructions toqiskit.quantum_info.Statevector.from_instruction()
. Note that this involves RNG sampling in choosing the projection to the zero state in the case where the qubit is in a superposition state. The seed for sampling can be set using theseed()
method. -
The methods
qiskit.circuit.ParameterExpression.subs()
andqiskit.circuit.QuantumCircuit.assign_parameters()
now acceptParameterExpression
as the target value to be substituted.For example,
from qiskit.circuit import QuantumCircuit , Parameter p = Parameter ( 'p' ) source = QuantumCircuit ( 1 ) source . rz ( p , 0 ) x = Parameter ( 'x' ) source . assign_parameters ({ p : x * x })
┌──────────┐ q_0: ┤ Rz(x**2) ├ └──────────┘
-
The
QuantumCircuit()
methodto_gate()
has a new kwarglabel
which can be used to set a label for for the outputGate
object. For example:from qiskit.circuit import QuantumCircuit circuit_gate = QuantumCircuit ( 2 ) circuit_gate . h ( 0 ) circuit_gate . cx ( 0 , 1 ) custom_gate = circuit_gate . to_gate ( label = 'My Special Bell' ) new_circ = QuantumCircuit ( 2 ) new_circ . append ( custom_gate , [ 0 , 1 ], []) new_circ . draw ( output = 'mpl' )
-
Added the
UGate
,CUGate
,PhaseGate
, andCPhaseGate
with the correspondingQuantumCircuit
methodsu()
,cu()
,p()
, andcp()
. TheUGate
gate is the generic single qubit rotation gate with 3 Euler angles and theCUGate
gate its controlled version.CUGate
has 4 parameters to account for a possible global phase of the U gate. ThePhaseGate
andCPhaseGate
gates are the general Phase gate at an arbitrary angle and it's controlled version. -
A new kwarg,
cregbundle
has been added to theqiskit.visualization.circuit_drawer()
function and theQuantumCircuit
methoddraw()
. When set toTrue
the cregs will be bundled into a single line in circuit visualizations for thetext
andmpl
drawers. The default value isTrue
. Addresses issue #4290.For example:
from qiskit import QuantumCircuit circuit = QuantumCircuit ( 2 ) circuit . measure_all () circuit . draw ( output = 'mpl' , cregbundle = True )
-
A new kwarg,
initial_state
has been added to theqiskit.visualization.circuit_drawer()
function and theQuantumCircuit
methoddraw()
. When set toTrue
the initial state will now be included in circuit visualizations for all drawers. Addresses issue #4293.For example:
from qiskit import QuantumCircuit circuit = QuantumCircuit ( 2 ) circuit . measure_all () circuit . draw ( output = 'mpl' , initial_state = True )
-
Labels will now be displayed when using the 'mpl' drawer. There are 2 types of labels - gate labels and control labels. Gate labels will replace the gate name in the display. Control labels will display above or below the controls for a gate. Fixes issues #3766, #4580 Addresses issues #3766 and #4580.
For example:
from qiskit import QuantumCircuit from qiskit.circuit.library.standard_gates import YGate circuit = QuantumCircuit ( 2 ) circuit . append ( YGate ( label = 'A Y Gate' ) . control ( label = 'Y Control' ), [ 0 , 1 ]) circuit . draw ( output = 'mpl' )
Upgrade Notes¶
-
Implementations of the multi-controlled X Gate (
MCXGrayCode
,MCXRecursive
, andMCXVChain
) have had theirname
properties changed to more accurately describe their implementation:mcx_gray
,mcx_recursive
, andmcx_vchain
respectively. Previously, these gates shared the namemcx
withMCXGate
, which caused these gates to be incorrectly transpiled and simulated. -
By default the preset passmanagers in
qiskit.transpiler.preset_passmanagers
are usingUnrollCustomDefinitions
andBasisTranslator
to handle basis changing instead of the previous defaultUnroller
. This was done because the new passes are more flexible and allow targeting any basis set, however the output may differ. To use the previous default you can set thetranslation_method
kwarg ontranspile()
to'unroller'
. -
The
qiskit.converters.circuit_to_gate()
and :func`qiskit.converters.circuit_to_instruction` converter functions had previously automatically included the generated gate or instruction in the activeSessionEquivalenceLibrary
. These converters now accept an optionalequivalence_library
keyword argument to specify if and where the converted instances should be registered. The default behavior has changed to not register the converted instance. -
The default value of the
cregbundle
kwarg for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
function has been changed toTrue
. This means that by default the classical bits in the circuit diagram will now be bundled by default, for example:from qiskit.circuit import QuantumCircuit circ = QuantumCircuit ( 4 ) circ . x ( 0 ) circ . h ( 1 ) circ . measure_all () circ . draw ( output = 'mpl' )
If you want to have your circuit drawing retain the previous behavior and show each classical bit in the diagram you can set the
cregbundle
kwarg toFalse
. For example:from qiskit.circuit import QuantumCircuit circ = QuantumCircuit ( 4 ) circ . x ( 0 ) circ . h ( 1 ) circ . measure_all () circ . draw ( output = 'mpl' , cregbundle = False )
-
Schedule
plotting withqiskit.pulse.Schedule.draw()
andqiskit.visualization.pulse_drawer()
will no longer display the event table by default. This can be reenabled by setting thetable
kwarg toTrue
. -
The pass
RemoveResetInZeroState
was previously included in the preset pass managerlevel_0_pass_manager()
which was used with theoptimization_level=0
fortranspile()
andexecute()
functions. However,RemoveResetInZeroState
is an optimization pass and should not have been included in optimization level 0 and was removed. If you need to runtranspile()
withRemoveResetInZeroState
either use a custom pass manager oroptimization_level
1, 2, or 3. -
The deprecated kwarg
line_length
for theqiskit.visualization.circuit_drawer()
function andqiskit.circuit.QuantumCircuit.draw()
method has been removed. It had been deprecated since the 0.10.0 release. Instead you can use thefold
kwarg to adjust the width of the circuit diagram. -
The
'mpl'
output mode for theqiskit.circuit.QuantumCircuit.draw()
method andcircuit_drawer()
now requires the pylatexenc library to be installed. This was already an optional dependency for visualization, but was only required for the'latex'
output mode before. It is now also required for the matplotlib drawer because it is needed to handle correctly sizing gates with matplotlib's mathtext labels for gates. -
The deprecated
get_tokens
methods for theqiskit.qasm.Qasm
andqiskit.qasm.QasmParser
has been removed. These methods have been deprecated since the 0.9.0 release. Theqiskit.qasm.Qasm.generate_tokens()
andqiskit.qasm.QasmParser.generate_tokens()
methods should be used instead. -
The deprecated kwarg
channels_to_plot
forqiskit.pulse.Schedule.draw()
,qiskit.pulse.Instruction.draw()
,qiskit.visualization.pulse.matplotlib.ScheduleDrawer.draw
andpulse_drawer()
has been removed. The kwarg has been deprecated since the 0.11.0 release and was replaced by thechannels
kwarg, which functions identically and should be used instead. -
The deprecated
circuit_instruction_map
attribute of theqiskit.providers.models.PulseDefaults
class has been removed. This attribute has been deprecated since the 0.12.0 release and was replaced by theinstruction_schedule_map
attribute which can be used instead. -
The
union
method ofSchedule
andInstruction
have been deprecated since the 0.12.0 release and have now been removed. Useqiskit.pulse.Schedule.insert()
andqiskit.pulse.Instruction.meth()
methods instead with the kwarg``time=0``. -
The deprecated
scaling
argument to thedraw
method ofSchedule
andInstruction
has been replaced withscale
since the 0.12.0 release and now has been removed. Use thescale
kwarg instead. -
The deprecated
period
argument toqiskit.pulse.library
functions have been replaced byfreq
since the 0.13.0 release and now removed. Use thefreq
kwarg instead ofperiod
. -
The
qiskit.pulse.commands
module containingCommands
classes was deprecated in the 0.13.0 release and has now been removed. You will have to upgrade your Pulse code if you were still using commands. For example:Old
New
Command(args)(channel)
Instruction(args, channel)
Acquire ( duration )( AcquireChannel ( 0 ))
Acquire ( duration , AcquireChannel ( 0 ))
Delay ( duration )( channel )
Delay ( duration , channel )
FrameChange ( angle )( DriveChannel ( 0 ))
# FrameChange was also renamed ShiftPhase ( angle , DriveChannel ( 0 ))
Gaussian ( ... )( DriveChannel ( 0 ))
# Pulses need to be `Play`d Play ( Gaussian ( ... ), DriveChannel ( 0 ))
-
All classes and function in the
qiskit.tool.qi
module were deprecated in the 0.12.0 release and have now been removed. Instead use theqiskit.quantum_info
module and the new methods and classes that it has for working with quantum states and operators. -
The
qiskit.quantum_info.basis_state
andqiskit.quantum_info.projector
functions are deprecated as of Qiskit Terra 0.12.0 as are now removed. Use theqiskit.quantum_info.QuantumState
and its derivativesqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
to work with states. -
The interactive plotting functions from
qiskit.visualization
,iplot_bloch_multivector
,iplot_state_city
,iplot_state_qsphere
,iplot_state_hinton
,iplot_histogram
,iplot_state_paulivec
now are just deprecated aliases for the matplotlib based equivalents and are no longer interactive. The hosted static JS code that these functions relied on has been removed and they no longer could work. A normal deprecation wasn't possible because the site they depended on no longer exists. -
The validation components using marshmallow from
qiskit.validation
have been removed from terra. Since they are no longer used to build any objects in terra. -
The marshmallow schema classes in
qiskit.result
have been removed since they are no longer used by theqiskit.result.Result
class. -
The output of the
to_dict()
method for theqiskit.result.Result
class is no longer in a format for direct JSON serialization. Depending on the content contained in instances of these classes there may be types that the default JSON encoder doesn't know how to handle, for example complex numbers or numpy arrays. If you're JSON serializing the output of theto_dict()
method directly you should ensure that your JSON encoder can handle these types. -
The option to acquire multiple qubits at once was deprecated in the 0.12.0 release and is now removed. Specifically, the init args
mem_slots
andreg_slots
have been removed fromqiskit.pulse.instructions.Acquire
, andchannel
,mem_slot
andreg_slot
will raise an error if a list is provided as input. -
Support for the use of the
USE_RETWORKX
environment variable which was introduced in the 0.13.0 release to provide an optional fallback to the legacy networkx basedqiskit.dagcircuit.DAGCircuit
implementation has been removed. This flag was only intended as provide a relief valve for any users that encountered a problem with the new implementation for one release during the transition to retworkx. -
The module within
qiskit.pulse
responsible for schedule->schedule transformations has been renamed fromreschedule.py
totransforms.py
. The previous import path has been deprecated. To upgrade your code:from qiskit.pulse.rescheduler import < X >
should be replaced by:
from qiskit.pulse.transforms import < X >
-
In previous releases a
PassManager
did not allowTransformationPass
classes to modify thePropertySet
. This restriction has been lifted so aTransformationPass
class now has read and write access to both thePropertySet
andDAGCircuit
duringrun()
. This change was made to more efficiently facilitateTransformationPass
classes that have an internal state which may be necessary for later passes in thePassManager
. Without this change a second redundantAnalysisPass
would have been necessary to recreate the internal state, which could add significant overhead.
Deprecation Notes¶
-
The name of the first positional parameter for the
qiskit.visualization
functionsplot_state_hinton()
,plot_bloch_multivector()
,plot_state_city()
,plot_state_paulivec()
, andplot_state_qsphere()
has been renamed fromrho
tostate
. Passing in the value by name torho
is deprecated and will be removed in a future release. Instead you should either pass the argument positionally or use the new parameter namestate
. -
The
qiskit.pulse.pulse_lib
module has been deprecated and will be removed in a future release. It has been renamed toqiskit.pulse.library
which should be used instead. -
The
qiskit.circuit.QuantumCircuit
methodmirror()
has been deprecated and will be removed in a future release. The methodqiskit.circuit.QuantumCircuit.reverse_ops()
should be used instead, since mirroring could be confused with swapping the output qubits of the circuit. Thereverse_ops()
method only reverses the order of gates that are applied instead of mirroring. -
The
qubits()
andclbits()
methods ofqiskit.dagcircuit.DAGCircuit
have been deprecated and will be removed in a future release. They have been replaced with properties of the same name,qiskit.dagcircuit.DAGCircuit.qubits
andqiskit.dagcircuit.DAGCircuit.clbits
, and are cached so accessing them is much faster. -
The
get_sample_pulse
method forqiskit.pulse.library.ParametricPulse
derived classes (for exampleGaussianSquare
) has been deprecated and will be removed in a future release. It has been replaced by theget_waveform
method (for exampleget_waveform()
) which should behave identically. -
The use of the optional
condition
argument onqiskit.dagcircuit.DAGNode
,qiskit.dagcircuit.DAGCircuit.apply_operation_back()
, andqiskit.dagcircuit.DAGCircuit.apply_operation_front()
has been deprecated and will be removed in a future release. Instead thecontrol
set inqiskit.circuit.Instruction
instances being added to aDAGCircuit
should be used. -
The
set_atol
andset_rtol
class methods of theqiskit.quantum_info.BaseOperator
andqiskit.quantum_info.QuantumState
classes (and their subclasses such asOperator
andqiskit.quantum_info.DensityMatrix
) are deprecated and will be removed in a future release. Instead the value for the attributes.atol
and.rtol
should be set on the class instead. For example:from qiskit.quantum_info import ScalarOp ScalarOp . atol = 3e-5 op = ScalarOp ( 2 )
-
The interactive plotting functions from
qiskit.visualization
,iplot_bloch_multivector
,iplot_state_city
,iplot_state_qsphere
,iplot_state_hinton
,iplot_histogram
,iplot_state_paulivec
have been deprecated and will be removed in a future release. The matplotlib based equivalent functions fromqiskit.visualization
,plot_bloch_multivector()
,plot_state_city()
,plot_state_qsphere()
,plot_state_hinton()
,plot_state_histogram()
, andplot_state_paulivec()
should be used instead. -
The properties
acquires
,mem_slots
, andreg_slots
of theqiskit.pulse.instructions.Acquire
pulse instruction have been deprecated and will be removed in a future release. They are just duplicates ofchannel
,mem_slot
, andreg_slot
respectively now that previously deprecated support for using multiple qubits in a singleAcquire
instruction has been removed. -
The
SamplePulse
class fromqiskit.pulse
has been renamed toWaveform
.SamplePulse
is deprecated and will be removed in a future release. -
The style dictionary key
cregbundle
has been deprecated and will be removed in a future release. This has been replaced by the kwargcregbundle
added to theqiskit.visualization.circuit_drawer()
function and theQuantumCircuit
methoddraw()
.
Bug Fixes¶
-
The
qiskit.circuit.QuantumCircuit
methodnum_nonlocal_gates
previously included multi-qubitqiskit.circuit.Instruction
objects (for example,Barrier
) in its count of non-local gates. This has been corrected so that only non-localGate
objects are counted. Fixes #4500 -
ControlledGate
instances with a setctrl_state
were in some cases not being evaluated as equal, even if the compared gates were equivalent. This has been resolved so that Fixes #4573 -
When accessing a bit from a
qiskit.circuit.QuantumRegister
orqiskit.circuit.ClassicalRegister
by index when using numpy integer types <https://numpy.org/doc/stable/user/basics.types.html>`__ would previously raise aCircuitError
exception. This has been resolved so numpy types can be used in addition to Python's built-inint
type. Fixes #3929. -
A bug was fixed where only the first
qiskit.pulse.configuration.Kernel
orqiskit.pulse.configuration.Discriminator
for anqiskit.pulse.Acquire
was used when there were multiple Acquires at the same time in aqiskit.pulse.Schedule
. -
The SI unit use for constructing
qiskit.pulse.SetFrequency
objects is in Hz, but when aPulseQobjInstruction
object is created from aSetFrequency
instance it needs to be converted to GHz. This conversion was missing from previous releases and has been fixed. -
Previously it was possible to set the number of control qubits to zero in which case the the original, potentially non-controlled, operation would be returned. This could cause an
AttributeError
to be raised if the caller attempted to access an attribute which onlyControlledGate
object have. This has been fixed by adding a getter and setter fornum_ctrl_qubits
to validate that a valid value is being used. Fixes #4576 -
Open controls were implemented by modifying a
Gate
objectsdefinition
. However, when the gate already exists in the basis set, this definition was not used, which resulted in incorrect circuits being sent to a backend after transpilation. This has been fixed by modifying theUnroller
pass to use the definition if it encounters a controlled gate with open controls. Fixes #4437 -
The
insert_barriers
keyword argument in theZZFeatureMap
class didn't actually insert barriers in between the Hadamard layers and evolution layers. This has been fixed so that barriers are now properly inserted. -
Fixed issue where some gates with three or more qubits would fail to compile in certain instances. Refer to #4577 <https://github.com/Qiskit/qiskit-terra/issues/4577 for more detail.
-
The matplotlib (
'mpl'
) output backend for theqiskit.circuit.QuantumCircuit
methoddraw()
and theqiskit.visualization.circuit_drawer()
function was not properly scaling when the kwargscale
was set. Fonts and line widths did not scale with the rest of the image. This has been fixed and all elements of the circuit diagram now scale properly. For example:from qiskit import QuantumCircuit circuit = QuantumCircuit ( 2 ) circuit . h ( 0 ) circuit . cx ( 0 , 1 ) circuit . draw ( output = 'mpl' , scale = 0.5 )
Fixes #4179.
-
Fixes issue where initializing or evolving
qiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes by circuits by circuit containingBarrier
instructions would raise an exception. Fixes #4461 -
Previously when a
QuantumCircuit
contained aGate
with a classical condition the transpiler would sometimes fail when usingoptimization_level=3
ontranspile()
orexecute()
raising anUnboundLocalError
. This has been fixed by updating theConsolidateBlocks
pass to account for the classical condition. Fixes #4672. -
In some situations long gate and register names would overflow, or leave excessive empty space around them when using the
'mpl'
output backend for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
function. This has been fixed by using correct text widths for a proportional font. Fixes #4611, #4605, #4545, #4497, #4449, and #3641. -
When using the
style` kwarg on the :meth:`qiskit.circuit.QuantumCircuit.draw` or :func:`qiskit.visualization.circuit_drawer` with the ``'mpl'
output backend the dictionary key'showindex'
set toTrue
, the index numbers at the top of the column did not line up properly. This has been fixed. -
When using
cregbunde=True
with the'mpl'
output backend for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
function and measuring onto a second fold, the measure arrow would overwrite the creg count. The count was moved to the left to prevent this. Fixes #4148. -
When using the
'mpl'
output backend for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
functionCSwapGate
gates and a controlledRZZGate
gates now display with their appropriate symbols instead of in a box. -
When using the
'mpl'
output backend for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
function controlled gates created using theto_gate()
method were not properly spaced and could overlap with other gates in the circuit diagram. This issue has been fixed. -
When using the
'mpl'
output backend for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
function gates with arrays as parameters, such asHamiltonianGate
, no longer display with excessive space around them. Fixes #4352. -
When using the
'mpl'
output backend for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
function generic gates created by directly instantiatingqiskit.circuit.Gate
method now display the proper background color for the gate. Fixes #4496. -
When using the
'mpl'
output backend for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
function anAttributeError
that occurred when usingIsometry
orInitialize
has been fixed. Fixes #4439. -
When using the
'mpl'
output backend for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
function some open-controlled gates did not properly display the open controls. This has been corrected so that open controls are properly displayed as open circles. Fixes #4248. -
When using the
'mpl'
output backend for theqiskit.circuit.QuantumCircuit.draw()
method andqiskit.visualization.circuit_drawer()
function setting thefold
kwarg to -1 will now properly display the circuit without folding. Fixes #4506. -
Parametric pulses from
qiskit.pulse.library.discrete
now have zero ends of parametric pulses by default. The endpoints are defined such that for a function \(f(x)\) then \(f(-1) = f(duration + 1) = 0\). Fixes #4317
Other Notes¶
-
The
qiskit.result.Result
class which was previously constructed using the marshmallow library has been refactored to not depend on marshmallow anymore. This new implementation should be a seamless transition but some specific behavior that was previously inherited from marshmallow may not work. Please file issues for any incompatibilities found.
Aer 0.6.1¶
Prelude¶
This 0.6.0 release includes numerous performance improvements for all simulators in the Aer provider and significant changes to the build system when building from source. The main changes are support for SIMD vectorization, approximation in the matrix product state method via bond-dimension truncation, more efficient Pauli expectation value computation, and greatly improved efficiency in Python conversion of C++ result objects. The build system was upgraded to use the Conan to manage common C++ dependencies when building from source.
New Features¶
-
Add density matrix snapshot support to "statevector" and "statevector_gpu" methods of the QasmSimulator.
-
Allow density matrix snapshots on specific qubits, not just all qubits. This computes the partial trace of the state over the remaining qubits.
-
Adds Pauli expectation value snapshot support to the "density_matrix" simulation method of the
qiskit.providers.aer.QasmSimulator
. Add snapshots to circuits using theqiskit.providers.aer.extensions.SnapshotExpectationValue
extension. -
Greatly improves performance of the Pauli expectation value snapshot algorithm for the "statevector", "statevector_gpu, "density_matrix", and "density_matrix_gpu" simulation methods of the
qiskit.providers.aer.QasmSimulator
. -
Enable the gate-fusion circuit optimization from the
qiskit.providers.aer.QasmSimulator
in both theqiskit.providers.aer.StatevectorSimulator
andqiskit.providers.aer.UnitarySimulator
backends. -
Improve the performance of average snapshot data in simulator results. This effects probability, Pauli expectation value, and density matrix snapshots using the following extensions:
-
qiskit.providers.aer.extensions.SnapshotExpectationValue
-
qiskit.providers.aer.extensions.SnapshotProbabilities
-
qiskit.providers.aer.extensions.SnapshotDensityMatrix
-
-
Add move constructor and improve memory usage of the C++ matrix class to minimize copies of matrices when moving output of simulators into results.
-
Improve performance of unitary simulator.
-
Add approximation to the "matrix_product_state" simulation method of the
QasmSimulator
to limit the bond-dimension of the MPS.There are two modes of approximation. Both discard the smallest Schmidt coefficients following the SVD algorithm. There are two parameters that control the degree of approximation:
"matrix_product_state_max_bond_dimension"
(int): Sets a limit on the number of Schmidt coefficients retained at the end of the svd algorithm. Coefficients beyond this limit will be discarded. (Default: None, i.e., no limit on the bond dimension)."matrix_product_state_truncation_threshold"
(double): Discard the smallest coefficients for which the sum of their squares is smaller than this threshold. (Default: 1e-16). -
Improve the performance of measure sampling when using the "matrix_product_state"
QasmSimulator
simulation method. -
Add support for
Delay
,Phase
andSetPhase
pulse instructions to theqiskit.providers.aer.PulseSimulator
. -
Improve the performance of the
qiskit.providers.aer.PulseSimulator
by caching calls to RHS function -
Introduce alternate DE solving methods, specifiable through
backend_options
in theqiskit.providers.aer.PulseSimulator
. -
Improve performance of simulator result classes by using move semantics and removing unnecessary copies that were happening when combining results from separate experiments into the final result object.
-
Greatly improve performance of pybind11 conversion of simulator results by using move semantics where possible, and by moving vector and matrix results to Numpy arrays without copies.
-
Change the RNG engine for simulators from 32-bit Mersenne twister to 64-bit Mersenne twister engine.
-
Improves the performance of the "statevector" simulation method of the
qiskit.providers.aer.QasmSimulator
andqiskit.providers.aer.StatevectorSimulator
by using SIMD intrinsics on systems that support the AVX2 instruction set. AVX2 support is automatically detected and enabled at runtime.
Upgrade Notes¶
-
Changes the build system to use the Conan package manager. This tool will handle most of the dependencies needed by the C++ source code. Internet connection may be needed for the first build or when dependencies are added or updated, in order to download the required packages if they are not in your Conan local repository.
When building the standalone version of qiskit-aer you must install conan first with:
-
Changes how transpilation passes are handled in the C++ Controller classes so that each pass must be explicitly called. This allows for greater customization on when each pass should be called, and with what parameters. In particular this enables setting different parameters for the gate fusion optimization pass depending on the QasmController simulation method.
-
Add
gate_length_units
kwarg toqiskit.providers.aer.noise.NoiseModel.from_device()
for specifying customgate_lengths
in the device noise model function to handle unit conversions for internal code. -
Add Controlled-Y ("cy") gate to the Stabilizer simulator methods supported gateset.
-
For Aer's backend the jsonschema validation of input qobj objects from terra is now opt-in instead of being enabled by default. If you want to enable jsonschema validation of qobj set the
validate
kwarg on theqiskit.providers.aer.QasmSimualtor.run()
method for the backend object toTrue
. -
Adds an OpSet object to the base simulator State class to allow easier validation of instructions, gates, and snapshots supported by simulators.
-
Refactor OpSet class. Moved OpSet to separate header file and add
contains
anddifference
methods based onstd::set::contains
andstd::algorithm::set_difference
. These replace the removed invalid and validate instructions from OpSet, but with the order reversed. It returns a list of other ops not in current opset rather than opset instructions not in the other. -
Improves how measurement sampling optimization is checked. The expensive part of this operation is now done once during circuit construction where rather than multiple times during simulation for when checking memory requirements, simulation method, and final execution.
Bug Fixes¶
-
Remove "extended_stabilizer" from the automatically selected simulation methods. This is needed as the extended stabilizer method is not exact and may give incorrect results for certain circuits unless the user knows how to optimize its configuration parameters.
The automatic method now only selects from "stabilizer", "density_matrix", and "statevector" methods. If a non-Clifford circuit that is too large for the statevector method is executed an exception will be raised suggesting you could try explicitly using the "extended_stabilizer" or "matrix_product_state" methods instead.
-
Disables gate fusion for the matrix product state simulation method as this was causing issues with incorrect results being returned in some cases.
-
Fixes a bug causing incorrect channel evaluation in the
qiskit.providers.aer.PulseSimulator
. -
Fixes several minor bugs for Hamiltonian parsing edge cases in the
qiskit.providers.aer.pulse.system_models.hamiltonian_model.HamiltonianModel
class.
Ignis 0.4.0¶
Prelude¶
The main change made in this release is a refactor of the Randomized Benchmarking code to integrate the updated Clifford class qiskit.quantum_info.Clifford
from Terra and to improve the CNOT-Dihedral class.
New Features¶
-
The
qiskit.ignis.verification.randomized_benchmarking.randomized_benchmarking_seq()
function was refactored to use the updated Clifford classClifford
, to allow efficient Randomized Benchmarking (RB) on Clifford sequences with more than 2 qubits. In addition, the code of the CNOT-Dihedral classqiskit.ignis.verification.randomized_benchmarking.CNOTDihedral
was refactored to make it more efficient, by using numpy arrays, as well not using pre-generated pickle files storing all the 2-qubit group elements. Theqiskit.ignis.verification.randomized_benchmarking.randomized_benchmarking_seq()
function has a new kwargrand_seed
which can be used to specify a seed for the random number generator used to generate the RB circuits. This can be useful for having a reproducible circuit. -
The
qiskit.ignis.verification.qv_circuits()
function has a new kwargseed
which can be used to specify a seed for the random number generator used to generate the Quantum Volume circuits. This can be useful for having a reproducible circuit.
Upgrade Notes¶
-
The
qiskit.ignis.verification.randomized_benchmarking.randomized_benchmarking_seq()
function is now using the updated Clifford classClifford
and the updated CNOT-Dihedral classqiskit.ignis.verification.randomized_benchmarking.CNOTDihedral
to construct its output instead of using pre-generated group tables for the Clifford and CNOT-Dihedral group elements, which were stored in pickle files. This may result in subtle differences from the output from the previous version. -
A new requirement scikit-learn has been added to the requirements list. This dependency was added in the 0.3.0 release but wasn't properly exposed as a dependency in that release. This would lead to an
ImportError
if theqiskit.ignis.measurement.discriminator.iq_discriminators
module was imported. This is now correctly listed as a dependency so thatscikit-learn
will be installed with qiskit-ignis. -
The
qiskit.ignis.verification.qv_circuits()
function is now using the circuit library classQuantumVolume
to construct its output instead of building the circuit from scratch. This may result in subtle differences from the output from the previous version. -
Tomography fitters can now also get list of Result objects instead of a single Result as requested in issue #320.
Deprecation Notes¶
-
The kwarg
interleaved_gates
for theqiskit.ignis.verification.randomized_benchmarking.randomized_benchmarking_seq()
function has been deprecated and will be removed in a future release. It is superseded byinterleaved_elem
. The helper functionsqiskit.ignis.verification.randomized_benchmarking.BasicUtils
,qiskit.ignis.verification.randomized_benchmarking.CliffordUtils
andqiskit.ignis.verification.randomized_benchmarking.DihedralUtils
were deprecated. These classes are superseded byqiskit.ignis.verification.randomized_benchmarking.RBgroup
that handles the group operations needed for RB. The classqiskit.ignis.verification.randomized_benchmarking.Clifford
is superseded byClifford
. -
The kwargs
qr
andcr
for theqiskit.ignis.verification.qv_circuits()
function have been deprecated and will be removed in a future release. These kwargs were documented as being used for specifying aqiskit.circuit.QuantumRegister
andqiskit.circuit.ClassicalRegister
to use in the generated Quantum Volume circuits instead of creating new ones. However, the parameters were never actually respected and a new Register would always be created regardless of whether they were set or not. This behavior is unchanged and these kwargs still do not have any effect, but are being deprecated prior to removal to avoid a breaking change for users who may have been setting either. -
Support for passing in subsets of qubits as a list in the
qubit_lists
parameter for theqiskit.ignis.verification.qv_circuits()
function has been deprecated and will removed in a future release. In the past this was used to specify a layout to run the circuit on a device. In other words if you had a 5 qubit device and wanted to run a 2 qubit QV circuit on qubits 1, 3, and 4 of that device. You would pass in[1, 3, 4]
as one of the lists inqubit_lists
, which would generate a 5 qubit virtual circuit and have qv applied to qubits 1, 3, and 4 in that virtual circuit. However, this functionality is not necessary and overlaps with the concept ofinitial_layout
in the transpiler and whether a circuit has been embedded with a layout set. Moving forward instead you should just runtranspile()
orexecute()
with initial layout set to do this. For example, running the above example would become:from qiskit import execute from qiskit.ignis.verification import qv_circuits initial_layout = [ 1 , 3 , 4 ] qv_circs , _ = qv_circuits ([ list ( range3 )]) execute ( qv_circuits , initial_layout = initial_layout )
Bug Fixes¶
-
Fix a bug of the position of measurement pulses inserted by py:func:qiskit.ignis.characterization.calibrations.pulse_schedules.drag_schedules. Fixes #465
Aqua 0.7.5¶
New Features¶
-
Removed soft dependency on CPLEX in ADMMOptimizer. Now default optimizers used by ADMMOptimizer are MinimumEigenOptimizer for QUBO problems and SlsqpOptimizer as a continuous optimizer. You can still use CplexOptimizer as an optimizer for ADMMOptimizer, but it should be set explicitly.
-
New Yahoo! finance provider created.
-
Introduced
QuadraticProgramConverter
which is an abstract class for converters. Addedconvert
/interpret
methods for converters instead ofencode
/decode
. Addedto_ising
andfrom_ising
toQuadraticProgram
class. Moved all parameters fromconvert
to constructor exceptname
. Created setter/getter for converter parameters. Addedauto_define_penalty
andinterpret
for``LinearEqualityToPenalty``. Now error messages of converters are more informative. -
Added an SLSQP optimizer
qiskit.optimization.algorithms.SlsqpOptimizer
as a wrapper of the corresponding SciPy optimization method. This is a classical optimizer, does not depend on quantum algorithms and may be used as a replacement forCobylaOptimizer
. -
Cobyla optimizer has been modified to accommodate a multi start feature introduced in the SLSQP optimizer. By default, the optimizer does not run in the multi start mode.
-
The
SummedOp
does a mathematically more correct check for equality, where expressions such asX + X == 2*X
andX + Z == Z + X
evaluate toTrue
.
Deprecation Notes¶
-
GSLS optimizer class deprecated
__init__
parametermax_iter
in favor ofmaxiter
. SPSA optimizer class deprecated__init__
parametermax_trials
in favor ofmaxiter
. optimize_svm function deprecatedmax_iters
parameter in favor ofmaxiter
. ADMMParameters class deprecated__init__
parametermax_iter
in favor ofmaxiter
. -
The ising convert classes
qiskit.optimization.converters.QuadraticProgramToIsing
andqiskit.optimization.converters.IsingToQuadraticProgram
have been deprecated and will be removed in a future release. Instead theqiskit.optimization.QuadraticProgram
methodsto_ising()
andfrom_ising()
should be used instead. -
The
pprint_as_string
method forqiskit.optimization.QuadraticProgram
has been deprecated and will be removed in a future release. Instead you should just run.pprint_as_string()
on the output fromto_docplex()
-
The
prettyprint
method forqiskit.optimization.QuadraticProgram
has been deprecated and will be removed in a future release. Instead you should just run.prettyprint()
on the output fromto_docplex()
Bug Fixes¶
-
Changed in python version 3.8: On macOS, the spawn start method is now the default. The fork start method should be considered unsafe as it can lead to crashes in subprocesses. However P_BFGS doesn't support spawn, so we revert to single process. Refer to #1109 <https://github.com/Qiskit/qiskit-aqua/issues/1109> for more details.
-
Binding parameters in the
CircuitStateFn
did not copy the value ofis_measurement
and always setis_measurement=False
. This has been fixed. -
Previously, SummedOp.to_matrix_op built a list MatrixOp's (with numpy matrices) and then summed them, returning a single MatrixOp. Some algorithms (for example vqe) require summing thousands of matrices, which exhausts memory when building the list of matrices. With this change, no list is constructed. Rather, each operand in the sum is converted to a matrix, added to an accumulator, and discarded.
-
Changing backends in VQE from statevector to qasm_simulator or real device was causing an error due to CircuitSampler incompatible reuse. VQE was changed to always create a new CircuitSampler and create a new expectation in case not entered by user. Refer to #1153 <https://github.com/Qiskit/qiskit-aqua/issues/1153> for more details.
-
Exchange and Wikipedia finance providers were fixed to correctly handle Quandl data. Refer to #775 <https://github.com/Qiskit/qiskit-aqua/issues/775> for more details. Fixes a divide by 0 error on finance providers mean vector and covariance matrix calculations. Refer to #781 <https://github.com/Qiskit/qiskit-aqua/issues/781> for more details.
-
The
ListOp.combo_fn
property has been lost in several transformations, such as converting to another operator type, traversing, reducing or multiplication. Now this attribute is propagated to the resulting operator. -
The evaluation of some operator expressions, such as of
SummedOp``s and evaluations with the ``CircuitSampler
did not treat coefficients correctly or ignored them completely. E.g. evaluating~StateFn(0 * (I + Z)) @ Plus
did not yield 0 or the normalization of~StateFn(I) @ ((Plus + Minus) / sqrt(2))
missed a factor ofsqrt(2)
. This has been fixed. -
OptimizationResult
included some public setters and class variables wereOptional
. This fix makes all class variables read-only so that mypy and pylint can check types more effectively.MinimumEigenOptimizer.solve
generated bitstrings in a result asstr
. This fix changed the result intoList[float]
as the other algorithms do. Some public classes related to optimization algorithms were missing in the documentation ofqiskit.optimization.algorithms
. This fix added all such classes to the docstring. #1131 <https://github.com/Qiskit/qiskit-aqua/issues/1131> for more details. -
OptimizationResult.__init__
did not check whether the sizes ofx
andvariables
match or not (they should match). This fix added the check to raise an error if they do not match and fixes bugs detected by the check. This fix also adds missing unit tests related toOptimizationResult.variable_names
andOptimizationResult.variables_dict
intest_converters
. #1167 <https://github.com/Qiskit/qiskit-aqua/issues/1167> for more details. -
Fix parameter binding in the
OperatorStateFn
, which did not bind parameters of the underlying primitive but just the coefficients. -
op.eval(other)
, whereop
is of typeOperatorBase
, sometimes silently returns a nonsensical value when the number of qubits inop
andother
are not equal. This fix results in correct behavior, which is to throw an error rather than return a value, because the input in this case is invalid. -
The
construct_circuit
method ofVQE
previously returned the expectation value to be evaluated as typeOperatorBase
. This functionality has been moved intoconstruct_expectation
andconstruct_circuit
returns a list of the circuits that are evaluated to compute the expectation value.
IBM Q Provider 0.8.0¶
New Features¶
-
IBMQBackend
now has a newreservations()
method that returns reservation information for the backend, with optional filtering. In addition, you can now useprovider.backends.my_reservations()
to query for your own reservations. -
qiskit.providers.ibmq.job.IBMQJob.result()
raises anIBMQJobFailureError
exception if the job has failed. The exception message now contains the reason the job failed, if the entire job failed for a single reason. -
A new attribute
client_version
was added toIBMQJob
andqiskit.result.Result
object retrieved viaqiskit.providers.ibmq.job.IBMQJob.result()
.client_version
is a dictionary with the key being the name and the value being the version of the client used to submit the job, such as Qiskit. -
The
least_busy()
function now takes a new, optional parameterreservation_lookahead
. If specified or defaulted to, a backend is considered unavailable if it has reservations in the nextn
minutes, wheren
is the value ofreservation_lookahead
. For example, if the default value of 60 is used, then any backends that have reservations in the next 60 minutes are considered unavailable. -
ManagedResults
now has a newcombine_results()
method that combines results from all managed jobs and returns a singleResult
object. ThisResult
object can be used, for example, inqiskit-ignis
fitter methods.
Upgrade Notes¶
-
Timestamps in the following fields are now in local time instead of UTC:
-
Backend properties returned by
qiskit.providers.ibmq.IBMQBackend.properties()
. -
Backend properties returned by
qiskit.providers.ibmq.job.IBMQJob.properties()
. -
estimated_start_time
andestimated_complete_time
inQueueInfo
, returned byqiskit.providers.ibmq.job.IBMQJob.queue_info()
. -
date
inResult
, returned byqiskit.providers.ibmq.job.IBMQJob.result()
.
In addition, the
datetime
parameter forqiskit.providers.ibmq.IBMQBackend.properties()
is also expected to be in local time unless it has UTC timezone information. -
-
websockets
8.0 or above is now required if Python 3.7 or above is used.websockets
7.0 will continue to be used for Python 3.6 or below. -
On Windows, the event loop policy is set to
WindowsSelectorEventLoopPolicy
instead of using the defaultWindowsProactorEventLoopPolicy
. This fixes the issue that theqiskit.providers.ibmq.job.IBMQJob.result()
method could hang on Windows. Fixes #691
Deprecation Notes¶
-
Use of
Qconfig.py
to save IBM Quantum Experience credentials is deprecated and will be removed in the next release. You should useqiskitrc
(the default) instead.
Bug Fixes¶
-
Fixes an issue wherein a call to
qiskit.providers.ibmq.IBMQBackend.jobs()
can hang if the number of jobs being returned is large. Fixes #674 -
Fixes an issue which would raise a
ValueError
when building error maps in Jupyter for backends that are offline. Fixes #706 -
qiskit.providers.ibmq.IBMQBackend.jobs()
will now return the correct list ofIBMQJob
objects when thestatus
kwarg is set to'RUNNING'
. -
The package metadata has been updated to properly reflect the dependency on
qiskit-terra
>= 0.14.0. This dependency was implicitly added as part of the 0.7.0 release but was not reflected in the package requirements so it was previously possible to installqiskit-ibmq-provider
with a version ofqiskit-terra
which was too old. Fixes #677
Qiskit 0.19.6¶
Ignis 0.3.3¶
Upgrade Notes¶
-
A new requirement scikit-learn has been added to the requirements list. This dependency was added in the 0.3.0 release but wasn't properly exposed as a dependency in that release. This would lead to an
ImportError
if theqiskit.ignis.measurement.discriminator.iq_discriminators
module was imported. This is now correctly listed as a dependency so thatscikit-learn
will be installed with qiskit-ignis.
Bug Fixes¶
-
Fixes an issue in qiskit-ignis 0.3.2 which would raise an
ImportError
whenqiskit.ignis.verification.tomography.fitters.process_fitter
was imported withoutcvxpy
being installed.
IBM Q Provider 0.7.2¶
No Change
Qiskit 0.19.5¶
Ignis 0.3.2¶
Bug Fixes¶
-
The
qiskit.ignis.verification.TomographyFitter.fit()
method has improved detection logic for the default fitter. Previously, thecvx
fitter method was used whenever cvxpy was installed. However, it was possible to install cvxpy without an SDP solver that would work for thecvx
fitter method. This logic has been reworked so that thecvx
fitter method is only used ifcvxpy
is installed and an SDP solver is present that can be used. Otherwise, thelstsq
fitter is used. -
Fixes an edge case in
qiskit.ignis.mitigation.measurement.fitters.MeasurementFitter.apply()
for input that has invalid or incorrect state labels that don't match the calibration circuit. Previously, this would not error and just return an empty result. Instead now this case is correctly caught and aQiskitError
exception is raised when using incorrect labels.
Aqua 0.7.3¶
Upgrade Notes¶
-
The cvxpy dependency which is required for the svm classifier has been removed from the requirements list and made an optional dependency. This is because installing cvxpy is not seamless in every environment and often requires a compiler be installed to run. To use the svm classifier now you'll need to install cvxpy by either running
pip install cvxpy<1.1.0
or to install it with aqua runningpip install qiskit-aqua[cvx]
.
Bug Fixes¶
-
The
compose
method of theCircuitOp
usedQuantumCircuit.combine
which has been changed to useQuantumCircuit.compose
. Using combine leads to the problem that composing an operator with aCircuitOp
based on a named register does not chain the operators but stacks them. E.g. composingZ ^ 2
with a circuit based on a 2-qubit named register yielded a 4-qubit operator instead of a 2-qubit operator. -
The
MatrixOp.to_instruction
method previously returned an operator and not an instruction. This method has been updated to return an Instruction. Note that this only works if the operator primitive is unitary, otherwise an error is raised upon the construction of the instruction. -
The
__hash__
method of thePauliOp
class used theid()
method which prevents set comparisons to work as expected since they rely on hash tables and identical objects used to not have identical hashes. Now, the implementation uses a hash of the string representation inline with the implementation in thePauli
class.
IBM Q Provider 0.7.2¶
No Change
Qiskit 0.19.4¶
Terra 0.14.2¶
Upgrade Notes¶
-
The
circuit_to_gate
andcircuit_to_instruction
converters had previously automatically included the generated gate or instruction in the activeSessionEquivalenceLibrary
. These converters now accept an optionalequivalence_library
keyword argument to specify if and where the converted instances should be registered. The default behavior is not to register the converted instance.
Bug Fixes¶
-
Implementations of the multi-controlled X Gate (
MCXGrayCode
,MCXRecursive
andMCXVChain
) have had theirname
properties changed to more accurately describe their implementation (mcx_gray
,mcx_recursive
, andmcx_vchain
respectively.) Previously, these gates shared the namemcx` with ``MCXGate
, which caused these gates to be incorrectly transpiled and simulated. -
ControlledGate
instances with a setctrl_state
were in some cases not being evaluated as equal, even if the compared gates were equivalent. This has been resolved. -
Fixed the SI unit conversion for
qiskit.pulse.SetFrequency
. TheSetFrequency
instruction should be in Hz on the frontend and has to be converted to GHz whenSetFrequency
is converted toPulseQobjInstruction
. -
Open controls were implemented by modifying a gate's definition. However, when the gate already exists in the basis, this definition is not used, which yields incorrect circuits sent to a backend. This modifies the unroller to output the definition if it encounters a controlled gate with open controls.
Aqua 0.7.2¶
Prelude¶
VQE expectation computation with Aer qasm_simulator now defaults to a computation that has the expected shot noise behavior.
Upgrade Notes¶
-
cvxpy is now in the requirements list as a dependency for qiskit-aqua. It is used for the quadratic program solver which is used as part of the
qiskit.aqua.algorithms.QSVM
. Previouslycvxopt
was an optional dependency that needed to be installed to use this functionality. This is no longer required as cvxpy will be installed with qiskit-aqua. -
For state tomography run as part of
qiskit.aqua.algorithms.HHL
with a QASM backend the tomography fitter functionqiskit.ignis.verification.StateTomographyFitter.fit()
now gets called explicitly with the method set tolstsq
to always use the least-squares fitting. Previously it would opportunistically try to use thecvx
fitter ifcvxpy
were installed. But, thecvx
fitter depends on a specifically configuredcvxpy
installation with an SDP solver installed as part ofcvxpy
which is not always present in an environment withcvxpy
installed. -
The VQE expectation computation using qiskit-aer's
qiskit.providers.aer.extensions.SnapshotExpectationValue
instruction is not enabled by default anymore. This was changed to be the default in 0.7.0 because it is significantly faster, but it led to unexpected ideal results without shot noise (see #1013 for more details). The default has now changed back to match user expectations. Using the faster expectation computation is now opt-in by setting the newinclude_custom
kwarg toTrue
on theqiskit.aqua.algorithms.VQE
constructor.
New Features¶
-
A new kwarg
include_custom
has been added to the constructor forqiskit.aqua.algorithms.VQE
and it's subclasses (mainlyqiskit.aqua.algorithms.QAOA
). When set to true and theexpectation
kwarg is set toNone
(the default) this will enable the use of VQE expectation computation with Aer'sqasm_simulator
qiskit.providers.aer.extensions.SnapshotExpectationValue
instruction. The special Aer snapshot based computation is much faster but with the ideal output similar to state vector simulator.
IBM Q Provider 0.7.2¶
No Change
Qiskit 0.19.3¶
Aer 0.5.2¶
Bug Fixes¶
-
Fixed bug with statevector and unitary simulators running a number of (parallel) shots equal to the number of CPU threads instead of only running a single shot.
-
Fixes the "diagonal" qobj gate instructions being applied incorrectly in the density matrix Qasm Simulator method.
-
Fixes bug where conditional gates were not being applied correctly on the density matrix simulation method.
-
Fix bug in CZ gate and Z gate for "density_matrix_gpu" and "density_matrix_thrust" QasmSimulator methods.
-
Fixes issue where memory requirements of simulation were not being checked on the QasmSimulator when using a non-automatic simulation method.
-
Fixed a memory leak that effected the GPU simulator methods
IBM Q Provider 0.7.2¶
Bug Fixes¶
-
qiskit.provider.ibmq.IBMQBackend.jobs()
will now return the correct list ofIBMQJob
objects when thestatus
kwarg is set to'RUNNING'
. Fixes #523 -
The package metadata has been updated to properly reflect the dependency on
qiskit-terra
>= 0.14.0. This dependency was implicitly added as part of the 0.7.0 release but was not reflected in the package requirements so it was previously possible to installqiskit-ibmq-provider
with a version ofqiskit-terra
which was too old. Fixes #677
Qiskit 0.19.0¶
Terra 0.14.0¶
Prelude¶
The 0.14.0 release includes several new features and bug fixes. The biggest change for this release is the introduction of a quantum circuit library in qiskit.circuit.library
, containing some circuit families of interest.
The circuit library gives users access to a rich set of well-studied circuit families, instances of which can be used as benchmarks, as building blocks in building more complex circuits, or as a tool to explore quantum computational advantage over classical. The contents of this library will continue to grow and mature.
The initial release of the circuit library contains:
-
standard_gates
: these are fixed-width gates commonly used as primitive building blocks, consisting of 1, 2, and 3 qubit gates. For example theXGate
,RZZGate
andCSWAPGate
. The old location of these gates underqiskit.extensions.standard
is deprecated. -
generalized_gates
: these are families that can generalize to arbitrarily many qubits, for example aPermutation
orGMS
(Global Molmer-Sorensen gate). -
boolean_logic
: circuits that transform basis states according to simple Boolean logic functions, such asADD
orXOR
. -
arithmetic
: a set of circuits for doing classical arithmetic such asWeightedAdder
andIntegerComparator
. -
basis_changes
: circuits such as the quantum Fourier transform,QFT
, that mathematically apply basis changes. -
n_local
: patterns to easily create large circuits with rotation and entanglement layers, such asTwoLocal
which uses single-qubit rotations and two-qubit entanglements. -
data_preparation
: circuits that take classical input data and encode it in a quantum state that is difficult to simulate, e.g.PauliFeatureMap
orZZFeatureMap
. -
Other circuits that have proven interesting in the literature, such as
QuantumVolume
,GraphState
, orIQP
.
To allow easier use of these circuits as building blocks, we have introduced a compose()
method of qiskit.circuit.QuantumCircuit
for composition of circuits either with other circuits (by welding them at the ends and optionally permuting wires) or with other simpler gates:
>>> lhs . compose ( rhs , qubits = [ 3 , 2 ], inplace = True )
┌───┐ ┌─────┐ ┌───┐ lqr_1_0: ───┤ H ├─── rqr_0: ──■──┤ Tdg ├ lqr_1_0: ───┤ H ├─────────────── ├───┤ ┌─┴─┐└─────┘ ├───┤ lqr_1_1: ───┤ X ├─── rqr_1: ┤ X ├─────── lqr_1_1: ───┤ X ├─────────────── ┌──┴───┴──┐ └───┘ ┌──┴───┴──┐┌───┐ lqr_1_2: ┤ U1(0.1) ├ + = lqr_1_2: ┤ U1(0.1) ├┤ X ├─────── └─────────┘ └─────────┘└─┬─┘┌─────┐ lqr_2_0: ─────■───── lqr_2_0: ─────■───────■──┤ Tdg ├ ┌─┴─┐ ┌─┴─┐ └─────┘ lqr_2_1: ───┤ X ├─── lqr_2_1: ───┤ X ├─────────────── └───┘ └───┘ lcr_0: 0 ═══════════ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════ lcr_1: 0 ═══════════════════════
With this, Qiskit's circuits no longer assume an implicit initial state of \(|0\rangle\), and will not be drawn with this initial state. The all-zero initial state is still assumed on a backend when a circuit is executed.
New Features¶
-
A new method,
has_entry()
, has been added to theqiskit.circuit.EquivalenceLibrary
class to quickly check if a given gate has any known decompositions in the library. -
A new class
IQP
, to construct an instantaneous quantum polynomial circuit, has been added to the circuit library moduleqiskit.circuit.library
. -
A new
compose()
method has been added toqiskit.circuit.QuantumCircuit
. It allows composition of two quantum circuits without having to turn one into a gate or instruction. It also allows permutations of qubits/clbits at the point of composition, as well as optional inplace modification. It can also be used in place ofappend()
, as it allows composing instructions and operators onto the circuit as well. -
qiskit.circuit.library.Diagonal
circuits have been added to the circuit library. These circuits implement diagonal quantum operators (consisting of non-zero elements only on the diagonal). They are more efficiently simulated by the Aer simulator than dense matrices. -
Add
from_label()
method to theqiskit.quantum_info.Clifford
class for initializing as the tensor product of single-qubit I, X, Y, Z, H, or S gates. -
Schedule transformer
qiskit.pulse.reschedule.compress_pulses()
performs an optimization pass to reduce the usage of waveform memory in hardware by replacing multiple identical instances of a pulse in a pulse schedule with a single pulse. For example:from qiskit.pulse import reschedule schedules = [] for _ in range ( 2 ): schedule = Schedule () drive_channel = DriveChannel ( 0 ) schedule += Play ( SamplePulse ([ 0.0 , 0.1 ]), drive_channel ) schedule += Play ( SamplePulse ([ 0.0 , 0.1 ]), drive_channel ) schedules . append ( schedule ) compressed_schedules = reschedule . compress_pulses ( schedules )
-
The
qiskit.transpiler.Layout
has a new methodreorder_bits()
that is used to reorder a list of virtual qubits based on the layout object. -
Two new methods have been added to the
qiskit.providers.models.PulseBackendConfiguration
for interacting with channels.-
get_channel_qubits()
to get a list of all qubits operated by the given channel and -
get_qubit_channel()
to get a list of channels operating on the given qubit.
-
-
New
qiskit.extensions.HamiltonianGate
andqiskit.circuit.QuantumCircuit.hamiltonian()
methods are introduced, representing Hamiltonian evolution of the circuit wavefunction by a user-specified Hermitian Operator and evolution time. The evolution time can be aParameter
, allowing the creation of parameterized UCCSD or QAOA-style circuits which compile toUnitaryGate
objects iftime
parameters are provided. The Unitary of aHamiltonianGate
with Hamiltonian OperatorH
and time parametert
is \(e^{-iHt}\). -
The circuit library module
qiskit.circuit.library
now provides a new boolean logic AND circuit,qiskit.circuit.library.AND
, and OR circuit,qiskit.circuit.library.OR
, which implement the respective operations on a variable number of provided qubits. -
New fake backends are added under
qiskit.test.mock
. These include mocked versions ofibmq_armonk
,ibmq_essex
,ibmq_london
,ibmq_valencia
,ibmq_cambridge
,ibmq_paris
,ibmq_rome
, andibmq_athens
. As with other fake backends, these include snapshots of calibration data (i.e.backend.defaults()
) and error data (i.e.backend.properties()
) taken from the real system, and can be used for local testing, compilation and simulation. -
The
last_update_date
parameter forBackendProperties
can now also be passed in as adatetime
object. Previously only a string in ISO8601 format was accepted. -
Adds
qiskit.quantum_info.Statevector.from_int()
andqiskit.quantum_info.DensityMatrix.from_int()
methods that allow constructing a computational basis state for specified system dimensions. -
The methods on the
qiskit.circuit.QuantumCircuit
class for adding gates (for exampleh()
) which were previously added dynamically at run time to the class definition have been refactored to be statically defined methods of the class. This means that static analyzer (such as IDEs) can now read these methods.
Upgrade Notes¶
-
A new package, python-dateutil, is now required and has been added to the requirements list. It is being used to parse datetime strings received from external providers in
BackendProperties
objects. -
The marshmallow schema classes in
qiskit.providers.models
have been removed since they are no longer used by the BackendObjects. -
The output of the
to_dict()
method for the classes inqiskit.providers.models
is no longer in a format for direct JSON serialization. Depending on the content contained in instances of these class there may be numpy arrays and/or complex numbers in the fields of the dict. If you're JSON serializing the output of the to_dict methods you should ensure your JSON encoder can handle numpy arrays and complex numbers. This includes:-
qiskit.providers.models.BackendConfiguration.to_dict()
-
qiskit.providers.models.BackendProperties.to_dict()
-
qiskit.providers.models.BackendStatus.to_dict()
-
qiskit.providers.models.QasmBackendConfiguration.to_dict()
-
qiskit.providers.models.PulseBackendConfiguration.to_dict()
-
qiskit.providers.models.UchannelLO.to_dict()
-
qiskit.providers.models.GateConfig.to_dict()
-
qiskit.providers.models.PulseDefaults.to_dict()
-
qiskit.providers.models.Command.to_dict()
-
qiskit.providers.models.JobStatus.to_dict()
-
qiskit.providers.models.Nduv.to_dict()
-
qiskit.providers.models.Gate.to_dict()
-
Deprecation Notes¶
-
The
qiskit.dagcircuit.DAGCircuit.compose()
method now takes a list of qubits/clbits that specify the positional order of bits to compose onto. The dictionary-based method of mapping using theedge_map
argument is deprecated and will be removed in a future release. -
The
combine_into_edge_map()
method for theqiskit.transpiler.Layout
class has been deprecated and will be removed in a future release. Instead, the new methodreorder_bits()
should be used to reorder a list of virtual qubits according to the layout object. -
Passing a
qiskit.pulse.ControlChannel
object in via the parameterchannel
for theqiskit.providers.models.PulseBackendConfiguration
methodcontrol()
has been deprecated and will be removed in a future release. TheControlChannel
objects are now generated from the backend configurationchannels
attribute which has the information of all channels and the qubits they operate on. Now, the methodcontrol()
is expected to take the parameterqubits
of the form(control_qubit, target_qubit)
and typelist
ortuple
, and returns a list of control channels. -
The
AND
andOR
methods ofqiskit.circuit.QuantumCircuit
are deprecated and will be removed in a future release. Instead you should use the circuit library boolean logic classesqiskit.circuit.library.AND
amdqiskit.circuit.library.OR
and then append those objects to your class. For example:from qiskit import QuantumCircuit from qiskit.circuit.library import AND qc = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc_and = AND ( 2 ) qc . compose ( qc_and , inplace = True )
-
The
qiskit.extensions.standard
module is deprecated and will be removed in a future release. The gate classes in that module have been moved toqiskit.circuit.library.standard_gates
.
Bug Fixes¶
-
The
qiskit.circuit.QuantumCircuit
methodsinverse()
,mirror()
methods, as well as theQuantumCircuit.data
setter would generate an invalid circuit when used on a parameterized circuit instance. This has been resolved and these methods should now work with a parameterized circuit. Fixes #4235 -
Previously when creating a controlled version of a standard qiskit gate if a
ctrl_state
was specified a genericControlledGate
object would be returned whereas without it a standard qiskit controlled gate would be returned if it was defined. This PR allows standard qiskit controlled gates to understandctrl_state
.Additionally, this PR fixes what might be considered a bug where setting the
ctrl_state
of an already controlled gate would assume the specified state applied to the full control width instead of the control qubits being added. For instance,:circ = QuantumCircuit ( 2 ) circ . h ( 0 ) circ . x ( 1 ) gate = circ . to_gate () cgate = gate . control ( 1 ) c3gate = cgate . control ( 2 , ctrl_state = 0 )
would apply
ctrl_state
to all three control qubits instead of just the two control qubits being added. -
Fixed a bug in
random_clifford()
that stopped it from sampling the full Clifford group. Fixes #4271 -
The
qiskit.circuit.Instruction
methodqiskit.circuit.Instruction.is_parameterized()
method had previously returnedTrue
for anyInstruction
instance which had aqiskit.circuit.Parameter
in any element of itsparams
array, even if thatParameter
had been fully bound. This has been corrected so that.is_parameterized
will returnFalse
when the instruction is fully bound. -
qiskit.circuit.ParameterExpression.subs()
had not correctly detected some cases where substituting parameters would result in a two distinctParameters
objects in an expression with the same name. This has been corrected so aCircuitError
will be raised in these cases. -
Improve performance of
qiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
for low-qubit circuit simulations by optimizing the class__init__
methods. Fixes #4281 -
The function
qiskit.compiler.transpile()
now correctly handles when the parameterbasis_gates
is set toNone
. This will allow any gate in the output tranpiled circuit, including gates added by the transpilation process. Note that using this parameter may have some unintended consequences during optimization. Some transpiler passes depend on having abasis_gates
set. For example,qiskit.transpiler.passes.Optimize1qGates
only optimizes the chains of u1, u2, and u3 gates and withoutbasis_gates
it is unable to unroll gates that otherwise could be optimized:from qiskit import * q = QuantumRegister ( 1 , name = 'q' ) circuit = QuantumCircuit ( q ) circuit . h ( q [ 0 ]) circuit . u1 ( 0.1 , q [ 0 ]) circuit . u2 ( 0.1 , 0.2 , q [ 0 ]) circuit . h ( q [ 0 ]) circuit . u3 ( 0.1 , 0.2 , 0.3 , q [ 0 ]) result = transpile ( circuit , basis_gates = None , optimization_level = 3 ) result . draw ()
┌───┐┌─────────────┐┌───┐┌─────────────────┐ q_0: ┤ H ├┤ U2(0.1,0.3) ├┤ H ├┤ U3(0.1,0.2,0.3) ├ └───┘└─────────────┘└───┘└─────────────────┘
Fixes #3017
Other Notes¶
-
The objects in
qiskit.providers.models
which were previously constructed using the marshmallow library have been refactored to not depend on marshmallow. This includes:-
BackendConfiguration
-
BackendProperties
-
BackendStatus
-
QasmBackendConfiguration
-
PulseBackendConfiguration
-
UchannelLO
-
GateConfig
-
PulseDefaults
-
Command
-
JobStatus
-
Nduv
-
Gate
These should be drop-in replacements without any noticeable change but specifics inherited from marshmallow may not work. Please file issues for any incompatibilities found.
-
Aqua 0.7.0¶
Prelude¶
The Qiskit Aqua 0.7.0 release introduces a lot of new functionality along with an improved integration with qiskit.circuit.QuantumCircuit
objects. The central contributions are the Qiskit's optimization module, a complete refactor on Operators, using circuits as native input for the algorithms and removal of the declarative JSON API.
Optimization module¶
The qiskit.optimization`
module now offers functionality for modeling and solving quadratic programs. It provides various near-term quantum and conventional algorithms, such as the MinimumEigenOptimizer
(covering e.g. VQE
or QAOA
) or CplexOptimizer
, as well as a set of converters to translate between different problem representations, such as QuadraticProgramToQubo
. See the changelog for a list of the added features.
Operator flow¶
The operator logic provided in qiskit.aqua.operators`
was completely refactored and is now a full set of tools for constructing physically-intuitive quantum computations. It contains state functions, operators and measurements and internally relies on Terra's Operator objects. Computing expectation values and evolutions was heavily simplified and objects like the ExpectationFactory
produce the suitable, most efficient expectation algorithm based on the Operator input type. See the changelog for a overview of the added functionality.
Native circuits¶
Algorithms commonly use parameterized circuits as input, for example the VQE, VQC or QSVM. Previously, these inputs had to be of type VariationalForm
or FeatureMap
which were wrapping the circuit object. Now circuits are natively supported in these algorithms, which means any individually constructed QuantumCircuit
can be passed to these algorithms. In combination with the release of the circuit library which offers a wide collection of circuit families, it is now easy to construct elaborate circuits as algorithm input.
Declarative JSON API¶
The ability of running algorithms using dictionaries as parameters as well as using the Aqua interfaces GUI has been removed.
IBM Q Provider 0.7.0¶
Bug Fixes¶
-
Fixed an issue where
nest_asyncio.apply()
may raise an exception if there is no asyncio loop due to threading.
Qiskit 0.18.3¶
Aer 0.5.1¶
Upgrade Notes¶
-
Changes how transpilation passes are handled in the C++ Controller classes so that each pass must be explicitly called. This allows for greater customization on when each pass should be called, and with what parameters. In particular this enables setting different parameters for the gate fusion optimization pass depending on the QasmController simulation method.
-
Add
gate_length_units
kwarg toqiskit.providers.aer.noise.NoiseModel.from_device()
for specifying customgate_lengths
in the device noise model function to handle unit conversions for internal code. -
Add Controlled-Y ("cy") gate to the Stabilizer simulator methods supported gateset.
-
For Aer's backend the jsonschema validation of input qobj objects from terra is now opt-in instead of being enabled by default. If you want to enable jsonschema validation of qobj set the
validate
kwarg on theqiskit.providers.aer.QasmSimualtor.run()
method for the backend object toTrue
.
Bug Fixes¶
-
Remove "extended_stabilizer" from the automatically selected simulation methods. This is needed as the extended stabilizer method is not exact and may give incorrect results for certain circuits unless the user knows how to optimize its configuration parameters.
The automatic method now only selects from "stabilizer", "density_matrix", and "statevector" methods. If a non-Clifford circuit that is too large for the statevector method is executed an exception will be raised suggesting you could try explicitly using the "extended_stabilizer" or "matrix_product_state" methods instead.
-
Fixes Controller classes so that the ReduceBarrier transpilation pass is applied first. This prevents barrier instructions from preventing truncation of unused qubits if the only instruction defined on them was a barrier.
-
Disables gate fusion for the matrix product state simulation method as this was causing issues with incorrect results being returned in some cases.
-
Fix error in gate time unit conversion for device noise model with thermal relaxation errors and gate errors. The error probability the depolarizing error was being calculated with gate time in microseconds, while for thermal relaxation it was being calculated in nanoseconds. This resulted in no depolarizing error being applied as the incorrect units would make the device seem to be coherence limited.
-
Fix bug in incorrect composition of QuantumErrors when the qubits of composed instructions differ.
-
Fix issue where the "diagonal" gate is checked to be unitary with too high a tolerance. This was causing diagonals generated from Numpy functions to often fail the test.
-
Fix remove-barrier circuit optimization pass to be applied before qubit trucation. This fixes an issue where barriers inserted by the Terra transpiler across otherwise inactive qubits would prevent them from being truncated.
IBM Q Provider 0.6.1¶
No Change
Qiskit 0.18.0¶
Terra 0.13.0¶
Prelude¶
The 0.13.0 release includes many big changes. Some highlights for this release are:
For the transpiler we have switched the graph library used to build the qiskit.dagcircuit.DAGCircuit
class which is the underlying data structure behind all operations to be based on retworkx for greatly improved performance. Circuit transpilation speed in the 0.13.0 release should be significanlty faster than in previous releases.
There has been a significant simplification to the style in which Pulse instructions are built. Now, Command
s are deprecated and a unified set of Instruction
s are supported.
The qiskit.quantum_info
module includes several new functions for generating random operators (such as Cliffords and quantum channels) and for computing the diamond norm of quantum channels; upgrades to the Statevector
and DensityMatrix
classes to support computing measurement probabilities and sampling measurements; and several new classes are based on the symplectic representation of Pauli matrices. These new classes include Clifford operators ( Clifford
), N-qubit matrices that are sparse in the Pauli basis ( SparsePauliOp
), lists of Pauli's ( PauliTable
), and lists of stabilizers ( StabilizerTable
).
This release also has vastly improved documentation across Qiskit, including improved documentation for the qiskit.circuit
, qiskit.pulse
and qiskit.quantum_info
modules.
Additionally, the naming of gate objects and QuantumCircuit
methods have been updated to be more consistent. This has resulted in several classes and methods being deprecated as things move to a more consistent naming scheme.
For full details on all the changes made in this release see the detailed release notes below.
New Features¶
-
Added a new circuit library module
qiskit.circuit.library
. This will be a place for constructors of commonly used circuits that can be used as building blocks for larger circuits or applications. -
The
qiskit.providers.BaseJob
class has four new methods:-
done()
-
running()
-
cancelled()
-
in_final_state()
These methods are used to check wheter a job is in a given job status.
-
-
Add ability to specify control conditioned on a qubit being in the ground state. The state of the control qubits is represented by an integer. For example:
from qiskit import QuantumCircuit from qiskit.extensions.standard import XGate qc = QuantumCircuit ( 4 ) cgate = XGate () . control ( 3 , ctrl_state = 6 ) qc . append ( cgate , [ 0 , 1 , 2 , 3 ])
Creates a four qubit gate where the fourth qubit gets flipped if the first qubit is in the ground state and the second and third qubits are in the excited state. If
ctrl_state
isNone
, the default, control is conditioned on all control qubits being excited. -
A new jupyter widget,
%circuit_library_info
has been added toqiskit.tools.jupyter
. This widget is used for visualizing details about circuits built from the circuit library. For examplefrom qiskit.circuit.library import XOR import qiskit.tools.jupyter circuit = XOR ( 5 , seed = 42 ) % circuit_library_info circuit
-
A new kwarg option,
formatted
, has been added toqiskit.circuit.QuantumCircuit.qasm()
. When set toTrue
the method will print a syntax highlighted version (using pygments) to stdout and returnNone
(which differs from the normal behavior of returning the QASM code as a string). -
A new kwarg option,
filename
, has been added toqiskit.circuit.QuantumCircuit.qasm()
. When set to a path the method will write the QASM code to that file. It will then continue to output as normal. -
A new instruction
SetFrequency
which allows users to change the frequency of thePulseChannel
. This is done in the following way:from qiskit.pulse import Schedule from qiskit.pulse import SetFrequency sched = pulse . Schedule () sched += SetFrequency ( 5.5e9 , DriveChannel ( 0 ))
In this example, the frequency of all pulses before the
SetFrequency
command will be the default frequency and all pulses applied to drive channel zero after theSetFrequency
command will be at 5.5 GHz. Users ofSetFrequency
should keep in mind any hardware limitations. -
A new method,
assign_parameters()
has been added to theqiskit.circuit.QuantumCircuit
class. This method accepts a parameter dictionary with both floats and Parameters objects in a single dictionary. In other words this new method allows you to bind floats, Parameters or both in a single dictionary.Also, by using the
inplace
kwarg it can be specified you can optionally modify the original circuit in place. By default this is set toFalse
and a copy of the original circuit will be returned from the method. -
A new method
num_nonlocal_gates()
has been added to theqiskit.circuit.QuantumCircuit
class. This method will return the number of gates in a circuit that involve 2 or or more qubits. These gates are more costly in terms of time and error to implement. -
The
qiskit.circuit.QuantumCircuit
methodiso()
for adding anIsometry
gate to the circuit has a new alias. You can now callqiskit.circuit.QuantumCircuit.isometry()
in addition to callingiso
. -
A
description
attribute has been added to theCouplingMap
class for storing a short description for different coupling maps (e.g. full, grid, line, etc.). -
A new method
compose()
has been added to theDAGCircuit
class for composing two circuits via their DAGs.dag_left . compose ( dag_right , edge_map = { right_qubit0 : self . left_qubit1 , right_qubit1 : self . left_qubit4 , right_clbit0 : self . left_clbit1 , right_clbit1 : self . left_clbit0 })
┌───┐ ┌─────┐┌─┐ lqr_1_0: ───┤ H ├─── rqr_0: ──■──┤ Tdg ├┤M├ ├───┤ ┌─┴─┐└─┬─┬─┘└╥┘ lqr_1_1: ───┤ X ├─── rqr_1: ┤ X ├──┤M├───╫─ ┌──┴───┴──┐ └───┘ └╥┘ ║ lqr_1_2: ┤ U1(0.1) ├ + rcr_0: ════════╬════╩═ = └─────────┘ ║ lqr_2_0: ─────■───── rcr_1: ════════╩══════ ┌─┴─┐ lqr_2_1: ───┤ X ├─── └───┘ lcr_0: ═══════════ lcr_1: ═══════════ ┌───┐ lqr_1_0: ───┤ H ├────────────────── ├───┤ ┌─────┐┌─┐ lqr_1_1: ───┤ X ├─────■──┤ Tdg ├┤M├ ┌──┴───┴──┐ │ └─────┘└╥┘ lqr_1_2: ┤ U1(0.1) ├──┼──────────╫─ └─────────┘ │ ║ lqr_2_0: ─────■───────┼──────────╫─ ┌─┴─┐ ┌─┴─┐ ┌─┐ ║ lqr_2_1: ───┤ X ├───┤ X ├──┤M├───╫─ └───┘ └───┘ └╥┘ ║ lcr_0: ═══════════════════╩════╬═ ║ lcr_1: ════════════════════════╩═
-
The mock backends in
qiskit.test.mock
now have a functionalrun()
method that will return results similar to the real devices. Ifqiskit-aer
is installed a simulation will be run with a noise model built from the device snapshot in the fake backend. Otherwise,qiskit.providers.basicaer.QasmSimulatorPy
will be used to run an ideal simulation. Additionally, if a pulse experiment is passed torun
and qiskit-aer is installed thePulseSimulator
will be used to simulate the pulse schedules. -
The
qiskit.result.Result()
methodget_counts()
will now return a list of all the counts available when there are multiple circuits in a job. This works whenget_counts()
is called with no arguments.The main consideration for this feature was for drawing all the results from multiple circuits in the same histogram. For example it is now possible to do something like:
from qiskit import execute from qiskit import QuantumCircuit from qiskit.providers.basicaer import BasicAer from qiskit.visualization import plot_histogram sim = BasicAer . get_backend ( 'qasm_simulator' ) qc = QuantumCircuit ( 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc . measure_all () result = execute ([ qc , qc , qc ], sim ) . result () plot_histogram ( result . get_counts ())
-
A new kwarg,
initial_state
has been added to theqiskit.visualization.circuit_drawer()
function and theQuantumCircuit
methoddraw()
. When set toTrue
the initial state will be included in circuit visualizations for all backends. For example:from qiskit import QuantumCircuit circuit = QuantumCircuit ( 2 ) circuit . measure_all () circuit . draw ( output = 'mpl' , initial_state = True )
-
It is now possible to insert a callable into a
qiskit.pulse.InstructionScheduleMap
which returns a newqiskit.pulse.Schedule
when it is called with parameters. For example:def test_func ( x ): sched = Schedule () sched += pulse_lib . constant ( int ( x ), amp_test )( DriveChannel ( 0 )) return sched inst_map = InstructionScheduleMap () inst_map . add ( 'f' , ( 0 ,), test_func ) output_sched = inst_map . get ( 'f' , ( 0 ,), 10 ) assert output_sched . duration == 10
-
Two new gate classes,
qiskit.extensions.iSwapGate
andqiskit.extensions.DCXGate
, along with theirQuantumCircuit
methodsiswap()
anddcx()
have been added to the standard extensions. These gates, which are locally equivalent to each other, can be used to enact particular XY interactions. A brief motivation for these gates can be found in: arxiv.org/abs/quant-ph/0209035 -
The
qiskit.providers.BaseJob
class now has a new methodwait_for_final_state()
that polls for the job status until the job reaches a final state (such asDONE
orERROR
). This method also takes an optionalcallback
kwarg which takes a Python callable that will be called during each iteration of the poll loop. -
The
search_width
andsearch_depth
attributes of theqiskit.transpiler.passes.LookaheadSwap
pass are now settable when initializing the pass. A larger search space can often lead to more optimized circuits, at the cost of longer run time. -
The number of qubits in
BackendConfiguration
can now be accessed via the propertynum_qubits
. It was previously only accessible via then_qubits
attribute. -
Two new methods,
angles()
andangles_and_phase()
, have been added to theqiskit.quantum_info.OneQubitEulerDecomposer
class. These methods will return the relevant parameters without validation, and calling theOneQubitEulerDecomposer
object will perform the full synthesis with validation. -
An
RR
decomposition basis has been added to theqiskit.quantum_info.OneQubitEulerDecomposer
for decomposing an arbitrary 2x2 unitary into a twoRGate
circuit. -
Adds the ability to set
qargs
to objects which are subclasses of the abstractBaseOperator
class. This is done by calling the objectop(qargs)
(whereop
is an operator class) and will return a shallow copy of the original object with a qargs property set. When such an object is used with thecompose()
ordot()
methods the internal value for qargs will be used when theqargs
method kwarg is not used. This allows for subsystem composition using binary operators, for example:from qiskit.quantum_info import Operator init = Operator . from_label ( 'III' ) x = Operator . from_label ( 'X' ) h = Operator . from_label ( 'H' ) init @ x ([ 0 ]) @ h ([ 1 ])
-
Adds
qiskit.quantum_info.Clifford
operator class to the quantum_info module. This operator is an efficient symplectic representation an N-qubit unitary operator from the Clifford group. This class includes ato_circuit()
method for compilation into aQuantumCircuit
of Clifford gates with a minimal number of CX gates for up to 3-qubits. It also providers general compilation for N > 3 qubits but this method is not optimal in the number of two-qubit gates. -
Adds
qiskit.quantum_info.SparsePauliOp
operator class. This is an efficient representaiton of an N-qubit matrix that is sparse in the Pauli basis and uses aqiskit.quantum_info.PauliTable
and vector of complex coefficients for its data structure.This class supports much of the same functionality of the
qiskit.quantum_info.Operator
class soSparsePauliOp
objects can be tensored, composed, scalar multiplied, added and subtracted.Numpy arrays or
Operator
objects can be converted to aSparsePauliOp
using the :class:`~qiskit.quantum_info.SparsePauliOp.from_operator method.SparsePauliOp
can be convered to a sparse csr_matrix or dense Numpy array using theto_matrix
method, or to anOperator
object using theto_operator
method.A
SparsePauliOp
can be iterated over in terms of itsPauliTable
components and coefficients, its coefficients and Pauli string labels using thelabel_iter()
method, and the (dense or sparse) matrix components using thematrix_iter()
method. -
Add
qiskit.quantum_info.diamond_norm()
function for computing the diamond norm (completely-bounded trace-norm) of a quantum channel. This can be used to compute the distance between two quantum channels usingdiamond_norm(chan1 - chan2)
. -
A new class
qiskit.quantum_info.PauliTable
has been added. This is an efficient symplectic representation of a list of N-qubit Pauli operators. Some features of this class are:-
PauliTable
objects may be composed, and tensored which will return aPauliTable
object with the combination of the operation (compose()
,dot()
,expand()
,tensor()
) between each element of the first table, with each element of the second table. -
Addition of two tables acts as list concatination of the terms in each table (
+
). -
Pauli tables can be sorted by lexicographic (tensor product) order or by Pauli weights (
sort()
). -
Duplicate elements can be counted and deleted (
unique()
). -
The PauliTable may be iterated over in either its native symplectic boolean array representation, as Pauli string labels (
label_iter()
), or as dense Numpy array or sparse CSR matrices (matrix_iter()
). -
Checking commutation between elements of the Pauli table and another Pauli (
commutes()
) or Pauli table (commutes_with_all()
)
See the
qiskit.quantum_info.PauliTable
class API documentation for additional details. -
-
Adds
qiskit.quantum_info.StabilizerTable
class. This is a subclass of theqiskit.quantum_info.PauliTable
class which includes a boolean phase vector along with the Pauli table array. This represents a list of Stabilizer operators which are real-Pauli operators with +1 or -1 coefficient. Because the stabilizer matrices are real the"Y"
label matrix is defined as[[0, 1], [-1, 0]]
. See the API documentation for additional information. -
Adds
qiskit.quantum_info.pauli_basis()
function which returns an N-qubit Pauli basis as aqiskit.quantum_info.PauliTable
object. The ordering of this basis can either be by standard lexicographic (tensor product) order, or by the number of non-identity Pauli terms (weight). -
Adds
qiskit.quantum_info.ScalarOp
operator class that represents a scalar multiple of an identity operator. This can be used to initialize an identity on arbitrary dimension subsystems and it will be implicitly converted to otherBaseOperator
subclasses (such as anqiskit.quantum_info.Operator
orqiskit.quantum_info.SuperOp
) when it is composed with, or added to, them.Example: Identity operator
from qiskit.quantum_info import ScalarOp , Operator X = Operator . from_label ( 'X' ) Z = Operator . from_label ( 'Z' ) init = ScalarOp ( 2 ** 3 ) # 3-qubit identity op = init @ X ([ 0 ]) @ Z ([ 1 ]) @ X ([ 2 ]) # Op XZX
-
A new method,
reshape()
, has been added to theqiskit.quantum_innfo.Operator
class that returns a shallow copy of an operator subclass with reshaped subsystem input or output dimensions. The combined dimensions of all subsystems must be the same as the original operator or an exception will be raised. -
Adds
qiskit.quantum_info.random_clifford()
for generating a randomqiskit.quantum_info.Clifford
operator. -
Add
qiskit.quantum_info.random_quantum_channel()
function for generating a random quantum channel with fixedChoi
-rank in theStinespring
representation. -
Add
qiskit.quantum_info.random_hermitian()
for generating a random HermitianOperator
. -
Add
qiskit.quantum_info.random_statevector()
for generating a randomStatevector
. -
Adds
qiskit.quantum_info.random_pauli_table()
for generating a randomqiskit.quantum_info.PauliTable
. -
Adds
qiskit.quantum_info.random_stabilizer_table()
for generating a randomqiskit.quantum_info.StabilizerTable
. -
Add a
num_qubits
attribute toqiskit.quantum_info.StateVector
andqiskit.quantum_info.DensityMatrix
classes. This returns the number of qubits for N-qubit states and returnsNone
for non-qubit states. -
Adds
to_dict()
andto_dict()
methods to convertqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
objects into Bra-Ket notation dictionary.Example
from qiskit.quantum_info import Statevector state = Statevector . from_label ( '+0' ) print ( state . to_dict ())
{'00': (0.7071067811865475+0j), '10': (0.7071067811865475+0j)}
from qiskit.quantum_info import DensityMatrix state = DensityMatrix . from_label ( '+0' ) print ( state . to_dict ())
{'00|00': (0.4999999999999999+0j), '10|00': (0.4999999999999999+0j), '00|10': (0.4999999999999999+0j), '10|10': (0.4999999999999999+0j)}
-
Adds
probabilities()
andprobabilities()
toqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes which return an array of measurement outcome probabilities in the computational basis for the specified subsystems.Example
from qiskit.quantum_info import Statevector state = Statevector . from_label ( '+0' ) print ( state . probabilities ())
from qiskit.quantum_info import DensityMatrix state = DensityMatrix . from_label ( '+0' ) print ( state . probabilities ())
-
Adds
probabilities_dict()
andprobabilities_dict()
toqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes which return a count-style dictionary array of measurement outcome probabilities in the computational basis for the specified subsystems.from qiskit.quantum_info import Statevector state = Statevector . from_label ( '+0' ) print ( state . probabilities_dict ())
{'00': 0.4999999999999999, '10': 0.4999999999999999}
from qiskit.quantum_info import DensityMatrix state = DensityMatrix . from_label ( '+0' ) print ( state . probabilities_dict ())
{'00': 0.4999999999999999, '10': 0.4999999999999999}
-
Add
sample_counts()
andsample_memory()
methods to theStatevector
andDensityMatrix
classes for sampling measurement outcomes on subsystems.Example:
Generate a counts dictionary by sampling from a statevector
from qiskit.quantum_info import Statevector psi = Statevector . from_label ( '+0' ) shots = 1024 # Sample counts dictionary counts = psi . sample_counts ( shots ) print ( 'Measure both:' , counts ) # Qubit-0 counts0 = psi . sample_counts ( shots , [ 0 ]) print ( 'Measure Qubit-0:' , counts0 ) # Qubit-1 counts1 = psi . sample_counts ( shots , [ 1 ]) print ( 'Measure Qubit-1:' , counts1 )
Measure both: {'00': 523, '10': 501} Measure Qubit-0: {'0': 1024} Measure Qubit-1: {'0': 496, '1': 528}
Return the array of measurement outcomes for each sample
from qiskit.quantum_info import Statevector psi = Statevector . from_label ( '-1' ) shots = 10 # Sample memory mem = psi . sample_memory ( shots ) print ( 'Measure both:' , mem ) # Qubit-0 mem0 = psi . sample_memory ( shots , [ 0 ]) print ( 'Measure Qubit-0:' , mem0 ) # Qubit-1 mem1 = psi . sample_memory ( shots , [ 1 ]) print ( 'Measure Qubit-1:' , mem1 )
Measure both: ['11' '11' '01' '11' '01' '01' '01' '11' '11' '11'] Measure Qubit-0: ['1' '1' '1' '1' '1' '1' '1' '1' '1' '1'] Measure Qubit-1: ['1' '1' '1' '1' '1' '0' '1' '1' '0' '0']
-
Adds a
measure()
method to theqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
quantum state classes. This allows sampling a single measurement outcome from the specified subsystems and collapsing the statevector to the post-measurement computational basis state. For examplefrom qiskit.quantum_info import Statevector psi = Statevector . from_label ( '+1' ) # Measure both qubits outcome , psi_meas = psi . measure () print ( "measure([0, 1]) outcome:" , outcome , "Post-measurement state:" ) print ( psi_meas ) # Measure qubit-1 only outcome , psi_meas = psi . measure ([ 1 ]) print ( "measure([1]) outcome:" , outcome , "Post-measurement state:" ) print ( psi_meas )
measure([0, 1]) outcome: 11 Post-measurement state: Statevector([0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], dims=(2, 2)) measure([1]) outcome: 0 Post-measurement state: Statevector([-0.+0.j, 1.+0.j, -0.+0.j, 0.+0.j], dims=(2, 2))
-
Adds a
reset()
method to theqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
quantum state classes. This allows reseting some or all subsystems to the \(|0\rangle\) state. For examplefrom qiskit.quantum_info import Statevector psi = Statevector . from_label ( '+1' ) # Reset both qubits psi_reset = psi . reset () print ( "Post reset state: " ) print ( psi_reset ) # Reset qubit-1 only psi_reset = psi . reset ([ 1 ]) print ( "Post reset([1]) state: " ) print ( psi_reset )
Post reset state: Statevector([1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], dims=(2, 2)) Post reset([1]) state: Statevector([-0.+0.j, 1.+0.j, -0.+0.j, 0.+0.j], dims=(2, 2))
-
A new visualization function
qiskit.visualization.visualize_transition()
for visualizing single qubit gate transitions has been added. It takes in a single qubit circuit and returns an animation of qubit state transitions on a Bloch sphere. To use this function you must have installed the dependencies for and configured globally a matplotlib animtion writer. You can refer to the matplotlib documentation for more details on this. However, in the default case simply ensuring that FFmpeg is installed is sufficient to use this function.It supports circuits with the following gates:
-
HGate
-
XGate
-
YGate
-
ZGate
-
RXGate
-
RYGate
-
RZGate
-
SGate
-
SdgGate
-
TGate
-
TdgGate
-
U1Gate
For example:
from qiskit.visualization import visualize_transition from qiskit import * qc = QuantumCircuit ( 1 ) qc . h ( 0 ) qc . ry ( 70 , 0 ) qc . rx ( 90 , 0 ) qc . rz ( 120 , 0 ) visualize_transition ( qc , fpg = 20 , spg = 1 , trace = True )
-
-
execute()
has a new kwargschedule_circuit
. By settingschedule_circuit=True
this enables scheduling of the circuit into aSchedule
. This allows users buildingqiskit.circuit.QuantumCircuit
objects to make use of custom scheduler methods, such as theas_late_as_possible
andas_soon_as_possible
methods. For example:job = execute ( qc , backend , schedule_circuit = True , scheduling_method = "as_late_as_possible" )
-
A new environment variable
QISKIT_SUPPRESS_PACKAGING_WARNINGS
can be set toY
ory
which will suppress the warnings aboutqiskit-aer
andqiskit-ibmq-provider
not being installed at import time. This is useful for users who are only running qiskit-terra (or just not qiskit-aer and/or qiskit-ibmq-provider) and the warnings are not an indication of a potential packaging problem. You can set the environment variable toN
orn
to ensure that warnings are always enabled even if the user config file is set to disable them. -
A new user config file option,
suppress_packaging_warnings
has been added. When set totrue
in your user config file like:[ default ] suppress_packaging_warnings = true
it will suppress the warnings about
qiskit-aer
andqiskit-ibmq-provider
not being installed at import time. This is useful for users who are only running qiskit-terra (or just not qiskit-aer and/or qiskit-ibmq-provider) and the warnings are not an indication of a potential packaging problem. If the user config file is set to disable the warnings this can be overriden by setting theQISKIT_SUPPRESS_PACKAGING_WARNINGS
toN
orn
-
qiskit.compiler.transpile()
has two new kwargs,layout_method
androuting_method
. These allow you to select a particular method for placement and routing of circuits on constrained architectures. For, example:transpile ( circ , backend , layout_method = 'dense' , routing_method = 'lookahead' )
will run
DenseLayout
layout pass andLookaheadSwap
routing pass. -
There has been a significant simplification to the style in which Pulse instructions are built.
With the previous style,
Command
s were called with channels to make anInstruction
. The usage of both commands and instructions was a point of confusion. This was the previous style:sched += Delay ( 5 )( DriveChannel ( 0 )) sched += ShiftPhase ( np . pi )( DriveChannel ( 0 )) sched += SamplePulse ([ 1.0 , ... ])( DriveChannel ( 0 )) sched += Acquire ( 100 )( AcquireChannel ( 0 ), MemorySlot ( 0 ))
or, equivalently (though less used):
sched += DelayInstruction ( Delay ( 5 ), DriveChannel ( 0 )) sched += ShiftPhaseInstruction ( ShiftPhase ( np . pi ), DriveChannel ( 0 )) sched += PulseInstruction ( SamplePulse ([ 1.0 , ... ]), DriveChannel ( 0 )) sched += AcquireInstruction ( Acquire ( 100 ), AcquireChannel ( 0 ), MemorySlot ( 0 ))
Now, rather than build a command and an instruction, each command has been migrated into an instruction:
sched += Delay ( 5 , DriveChannel ( 0 )) sched += ShiftPhase ( np . pi , DriveChannel ( 0 )) sched += Play ( SamplePulse ([ 1.0 , ... ]), DriveChannel ( 0 )) sched += SetFrequency ( 5.5 , DriveChannel ( 0 )) # New instruction! sched += Acquire ( 100 , AcquireChannel ( 0 ), MemorySlot ( 0 ))
-
There is now a
Play
instruction which takes a description of a pulse envelope and a channel. There is a newPulse
class in thepulse_lib
from which the pulse envelope description should subclass.For example:
Play ( SamplePulse ([ 0.1 ] * 10 ), DriveChannel ( 0 )) Play ( ConstantPulse ( duration = 10 , amp = 0.1 ), DriveChannel ( 0 ))
Upgrade Notes¶
-
The
qiskit.dagcircuit.DAGNode
methodpop
which was deprecated in the 0.9.0 release has been removed. If you were using this method you can leverage Python'sdel
statement ordelattr()
function to perform the same task. -
A new optional visualization requirement, pygments , has been added. It is used for providing syntax highlighting of OpenQASM 2.0 code in Jupyter widgets and optionally for the
qiskit.circuit.QuantumCircuit.qasm()
method. It must be installed (either withpip install pygments
orpip install qiskit-terra[visualization]
) prior to using the%circuit_library_info
widget inqiskit.tools.jupyter
or theformatted
kwarg on theqasm()
method. -
The pulse
buffer
option found inqiskit.pulse.Channel
andqiskit.pulse.Schedule
was deprecated in Terra 0.11.0 and has now been removed. To add a delay on a channel or in a schedule, specify it explicitly in your Schedule with a Delay:sched = Schedule () sched += Delay ( 5 )( DriveChannel ( 0 ))
-
PulseChannelSpec
, which was deprecated in Terra 0.11.0, has now been removed. Use BackendConfiguration instead:config = backend . configuration () drive_chan_0 = config . drives ( 0 ) acq_chan_0 = config . acquires ( 0 )
or, simply reference the channel directly, such as
DriveChannel(index)
. -
An import path was deprecated in Terra 0.10.0 and has now been removed: for
PulseChannel
,DriveChannel
,MeasureChannel
, andControlChannel
, usefrom qiskit.pulse.channels import X
in place offrom qiskit.pulse.channels.pulse_channels import X
. -
The pass
qiskit.transpiler.passes.CSPLayout
(which was introduced in the 0.11.0 release) has been added to the preset pass manager for optimization levels 2 and 3. For level 2, there is a call limit of 1,000 and a timeout of 10 seconds. For level 3, the call limit is 10,000 and the timeout is 1 minute.Now that the pass is included in the preset pass managers the python-constraint package is not longer an optional dependency and has been added to the requirements list.
-
The
TranspileConfig
class which was previously used to set run time configuration for aqiskit.transpiler.PassManager
has been removed and replaced by a new classqiskit.transpile.PassManagerConfig
. This new class has been structured to include only the information needed to construct aPassManager
. The attributes of this class are:-
initial_layout
-
basis_gates
-
coupling_map
-
backend_properties
-
seed_transpiler
-
-
The function
transpile_circuit
inqiskit.transpiler
has been removed. To transpile a circuit with a customPassManager
now you should use therun()
method of the :class:~qiskit.transpiler.PassManager` object. -
The
QuantumCircuit
methoddraw()
andqiskit.visualization.circuit_drawer()
function will no longer include the initial state included in visualizations by default. If you would like to retain the initial state in the output visualization you need to set theinitial_state
kwarg toTrue
. For example, running:from qiskit import QuantumCircuit circuit = QuantumCircuit ( 2 ) circuit . measure_all () circuit . draw ( output = 'text' )
░ ┌─┐ q_0: ─░─┤M├─── ░ └╥┘┌─┐ q_1: ─░──╫─┤M├ ░ ║ └╥┘ meas: 2/════╩══╩═ 0 1
This no longer includes the initial state. If you'd like to retain it you can run:
from qiskit import QuantumCircuit circuit = QuantumCircuit ( 2 ) circuit . measure_all () circuit . draw ( output = 'text' , initial_state = True )
░ ┌─┐ q_0: |0>─░─┤M├─── ░ └╥┘┌─┐ q_1: |0>─░──╫─┤M├ ░ ║ └╥┘ meas: 0 2/════╩══╩═ 0 1
-
qiskit.compiler.transpile()
(andqiskit.execute.execute()
, which usestranspile
internally) will now raise an error when thepass_manager
kwarg is set and a value is set for other kwargs that are already set in an instantiatedPassManager
object. Previously, these conflicting kwargs would just be silently ignored and the values in thePassManager
instance would be used. For example:from qiskit.circuit import QuantumCircuit from qiskit.transpiler.pass_manager_config import PassManagerConfig from qiskit.transpiler import preset_passmanagers from qiskit.compiler import transpile qc = QuantumCircuit ( 5 ) config = PassManagerConfig ( basis_gates = [ 'u3' , 'cx' ]) pm = preset_passmanagers . level_0_pass_manager ( config ) transpile ( qc , optimization_level = 3 , pass_manager = pm )
will now raise an error while prior to this release the value in
pm
would just silently be used and the value for theoptimization_level
kwarg would be ignored. Thetranspile
kwargs this applies to are:-
optimization_level
-
basis_gates
-
coupling_map
-
seed_transpiler
-
backend_properties
-
initial_layout
-
layout_method
-
routing_method
-
backend
-
-
The
Operator
,Clifford
,SparsePauliOp
,PauliTable
,StabilizerTable
, operator classes have an addedcall
method that allows them to assign a qargs to the operator for use with thecompose()
,dot()
,evolve()
,``+``, and-
operations. -
The addition method of the
qiskit.quantum_info.Operator
, class now accepts aqarg
kwarg to allow adding a smaller operator to a larger one assuming identities on the other subsystems (same as forqargs
oncompose()
anddot()
methods). This allows subsystem addition using the call method as with composition. This support is added to all BaseOperator subclasses (ScalarOp
,Operator
,QuantumChannel
).For example:
from qiskit.quantum_info import Operator , ScalarOp ZZ = Operator . from_label ( 'ZZ' ) # Initialize empty Hamiltonian n_qubits = 10 ham = ScalarOp ( 2 ** n_qubits , coeff = 0 ) # Add 2-body nearest neighbour terms for j in range ( n_qubits - 1 ): ham = ham + ZZ ([ j , j + 1 ])
-
The
BaseOperator
class has been updated so that addition, subtraction and scalar multiplication are no longer abstract methods. This means that they are no longer required to be implemented in subclasses if they are not supported. The base class will raise aNotImplementedError
when the methods are not defined. -
The
qiskit.quantum_info.random_density_matrix()
function will now return a randomDensityMatrix
object. In previous releases it returned a numpy array. -
The
qiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes no longer copy the input array if it is already the correct dtype. -
fastjsonschema is added as a dependency. This is used for much faster validation of qobj dictionaries against the JSON schema when the
to_dict()
method is called on qobj objects with thevalidate
keyword argument set toTrue
. -
The qobj construction classes in
qiskit.qobj
will no longer validate against the qobj jsonschema by default. These include the following classes:-
qiskit.qobj.QasmQobjInstruction
-
qiskit.qobj.QobjExperimentHeader
-
qiskit.qobj.QasmQobjExperimentConfig
-
qiskit.qobj.QasmQobjExperiment
-
qiskit.qobj.QasmQobjConfig
-
qiskit.qobj.QobjHeader
-
qiskit.qobj.PulseQobjInstruction
-
qiskit.qobj.PulseQobjExperimentConfig
-
qiskit.qobj.PulseQobjExperiment
-
qiskit.qobj.PulseQobjConfig
-
qiskit.qobj.QobjMeasurementOption
-
qiskit.qobj.PulseLibraryItem
-
qiskit.qobj.QasmQobjInstruction
-
qiskit.qobj.QasmQobjExperimentConfig
-
qiskit.qobj.QasmQobjExperiment
-
qiskit.qobj.QasmQobjConfig
-
qiskit.qobj.QasmQobj
-
qiskit.qobj.PulseQobj
If you were relying on this validation or would like to validate them against the qobj schema this can be done by setting the
validate
kwarg toTrue
onto_dict()
method from either of the top level Qobj classesQasmQobj
orPulseQobj
. For example:which will validate the output dictionary against the Qobj jsonschema.
-
-
The output dictionary from
qiskit.qobj.QasmQobj.to_dict()
andqiskit.qobj.PulseQobj.to_dict()
is no longer in a format for direct json serialization as expected by IBMQ's API. These Qobj objects are the current format we use for passing experiments to providers/backends and while having a dictionary format that could just be passed to the IBMQ API directly was moderately useful forqiskit-ibmq-provider
, it made things more difficult for other providers. Especially for providers that wrap local simulators. Moving forward the definitions of what is passed between providers and the IBMQ API request format will be further decoupled (in a backwards compatible manner) which should ease the burden of writing providers and backends.In practice, the only functional difference between the output of these methods now and previous releases is that complex numbers are represented with the
complex
type and numpy arrays are not silently converted to list anymore. If you were previously callingjson.dumps()
directly on the output ofto_dict()
after this release a custom json encoder will be needed to handle these cases. For example:import json from qiskit.circuit import ParameterExpression from qiskit import qobj my_qasm = qobj . QasmQobj ( qobj_id = '12345' , header = qobj . QobjHeader (), config = qobj . QasmQobjConfig ( shots = 1024 , memory_slots = 2 , max_credits = 10 ), experiments = [ qobj . QasmQobjExperiment ( instructions = [ qobj . QasmQobjInstruction ( name = 'u1' , qubits = [ 1 ], params = [ 0.4 ]), qobj . QasmQobjInstruction ( name = 'u2' , qubits = [ 1 ], params = [ 0.4 , 0.2 ]) ]) ] ) qasm_dict = my_qasm . to_dict () class QobjEncoder ( json . JSONEncoder ): """A json encoder for pulse qobj""" def default ( self , obj ): # Convert numpy arrays: if hasattr ( obj , 'tolist' ): return obj . tolist () # Use Qobj complex json format: if isinstance ( obj , complex ): return ( obj . real , obj . imag ) if isinstance ( obj , ParameterExpression ): return float ( obj ) return json . JSONEncoder . default ( self , obj ) json_str = json . dumps ( qasm_dict , cls = QobjEncoder )
will generate a json string in the same exact manner that
json.dumps(my_qasm.to_dict())
did in previous releases. -
CmdDef
has been deprecated since Terra 0.11.0 and has been removed. Please continue to useInstructionScheduleMap
instead. -
The methods
cmds
andcmd_qubits
inInstructionScheduleMap
have been deprecated since Terra 0.11.0 and have been removed. Please useinstructions
andqubits_with_instruction
instead. -
PulseDefaults have reported
qubit_freq_est
andmeas_freq_est
in Hz rather than GHz since Terra release 0.11.0. A warning which notified of this change has been removed. -
The previously deprecated (in the 0.11.0 release) support for passsing in
qiskit.circuit.Instruction
parameters of typessympy.Basic
,sympy.Expr
,qiskit.qasm.node.node.Node
(QASM AST node) andsympy.Matrix
has been removed. The supported types for instruction parameters are:-
int
-
float
-
complex
-
str
-
list
-
np.ndarray
-
qiskit.circuit.ParameterExpression
-
-
The following properties of
BackendConfiguration
:-
dt
-
dtm
-
rep_time
all have units of seconds. Prior to release 0.11.0,
dt
anddtm
had units of nanoseconds. Prior to release 0.12.0,rep_time
had units of microseconds. The warnings alerting users of these changes have now been removed fromBackendConfiguration
. -
-
A new requirement has been added to the requirements list, retworkx. It is an Apache 2.0 licensed graph library that has a similar API to networkx and is being used to significantly speed up the
qiskit.dagcircuit.DAGCircuit
operations as part of the transpiler. There are binaries published on PyPI for all the platforms supported by Qiskit Terra but if you're using a platform where there aren't precompiled binaries published refer to the retworkx documentation for instructions on pip installing from sdist.If you encounter any issues with the transpiler or DAGCircuit class as part of the transition you can switch back to the previous networkx implementation by setting the environment variable
USE_RETWORKX
toN
. This option will be removed in the 0.14.0 release.
Deprecation Notes¶
-
Passing in the data to the constructor for
qiskit.dagcircuit.DAGNode
as a dictionary argdata_dict
is deprecated and will be removed in a future release. Instead you should now pass the fields in as kwargs to the constructor. For example the previous behavior of:from qiskit.dagcircuit import DAGNode data_dict = { 'type' : 'in' , 'name' : 'q_0' , } node = DAGNode ( data_dict )
should now be:
from qiskit.dagcircuit import DAGNode node = DAGNode ( type = 'in' , name = 'q_0' )
-
The naming of gate objects and methods have been updated to be more consistent. The following changes have been made:
-
The Pauli gates all have one uppercase letter only (
I
,X
,Y
,Z
) -
The parameterized Pauli gates (i.e. rotations) prepend the uppercase letter
R
(RX
,RY
,RZ
) -
A controlled version prepends the uppercase letter
C
(CX
,CRX
,CCX
) -
Gates are named according to their action, not their alternative names (
CCX
, notToffoli
)
The old names have been deprecated and will be removed in a future release. This is a list of the changes showing the old and new class, name attribute, and methods. If a new column is blank then there is no change for that.
Table 2 Gate Name Changes¶ Old Class
New Class
Old Name Attribute
New Name Attribute
Old
qiskit.circuit.QuantumCircuit
methodNew
qiskit.circuit.QuantumCircuit
methodToffoliGate
CCXGate
ccx
ccx()
andtoffoli()
CrxGate
CRXGate
crx
crx()
CryGate
CRYGate
cry
cry()
CrzGate
CRZGate
crz
crz()
FredkinGate
CSwapGate
cswap
cswap()
andfredkin()
Cu1Gate
CU1Gate
cu1
cu1()
Cu3Gate
CU3Gate
cu3
cu3()
CnotGate
CXGate
cx
cx()
andcnot()
CyGate
CYGate
cy
cy()
CzGate
CZGate
cz
cz()
DiagGate
DiagonalGate
diag
diagonal
diag_gate
diagonal()
IdGate
IGate
id
iden
i()
andid()
Isometry
iso
isometry
iso()
isometry()
andiso()
UCG
UCGate
multiplexer
ucg
uc()
UCRot
UCPauliRotGate
UCX
UCRXGate
ucrotX
ucrx
ucx
ucrx()
UCY
UCRYGate
ucroty
ucry
ucy
ucry()
UCZ
UCRZGate
ucrotz
ucrz
ucz
ucrz()
-
-
The kwarg
period
for the functionsquare()
,sawtooth()
, andtriangle()
inqiskit.pulse.pulse_lib
is now deprecated and will be removed in a future release. Instead you should now use thefreq
kwarg to set the frequency. -
The
DAGCircuit.compose_back()
andDAGCircuit.extend_back()
methods are deprecated and will be removed in a future release. Instead you should use theqiskit.dagcircuit.DAGCircuit.compose()
method, which is a more general and more flexible method that provides the same functionality. -
The
callback
kwarg of theqiskit.transpiler.PassManager
class's constructor has been deprecated and will be removed in a future release. Instead of setting it at the object level during creation it should now be set as a kwarg parameter on theqiskit.transpiler.PassManager.run()
method. -
The
n_qubits
andnumberofqubits
keywords are deprecated throughout Terra and replaced bynum_qubits
. The old names will be removed in a future release. The objects affected by this change are listed below:Table 3 New Methods¶ Class
Old Method
New Method
QuantumCircuit
n_qubits
num_qubits()
Pauli
numberofqubits
num_qubits()
Table 4 New arguments¶ Function
Old Argument
New Argument
random_circuit()
n_qubits
num_qubits
MSGate
n_qubit
num_qubits
-
The function
qiskit.quantum_info.synthesis.euler_angles_1q
is now deprecated. It has been superseded by theqiskit.quantum_info.OneQubitEulerDecomposer
class which provides the same functionality through:OneQubitEulerDecomposer () . angles ( mat )
-
The
pass_manager
kwarg for theqiskit.compiler.transpile()
has been deprecated and will be removed in a future release. Moving forward the preferred way to transpile a circuit with a customPassManager
object is to use therun()
method of thePassManager
object. -
The
qiskit.quantum_info.random_state()
function has been deprecated and will be removed in a future release. Instead you should use theqiskit.quantum_info.random_statevector()
function. -
The
add
,subtract
, andmultiply
methods of theqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes are deprecated and will be removed in a future release. Instead you shoulde use+
,-
,*
binary operators instead. -
Deprecates
qiskit.quantum_info.Statevector.to_counts()
,qiskit.quantum_info.DensityMatrix.to_counts()
, andqiskit.quantum_info.counts.state_to_counts()
. These functions are superseded by the class methodsqiskit.quantum_info.Statevector.probabilities_dict()
andqiskit.quantum_info.DensityMatrix.probabilities_dict()
. -
SamplePulse
andParametricPulse
s (e.g.Gaussian
) now subclass fromPulse
and have been moved to theqiskit.pulse.pulse_lib
. The previous path viapulse.commands
is deprecated and will be removed in a future release. -
DelayInstruction
has been deprecated and replaced byDelay
. This new instruction has been taken over the previousCommand
Delay
. The migration pattern is:Delay ( < duration > )( < channel > ) -> Delay ( < duration > , < channel > ) DelayInstruction ( Delay ( < duration > ), < channel > ) -> Delay ( < duration > , < channel > )
Until the deprecation period is over, the previous
Delay
syntax of calling a command on a channel will also be supported:Delay ( < phase > )( < channel > )
The new
Delay
instruction does not support acommand
attribute. -
FrameChange
andFrameChangeInstruction
have been deprecated and replaced byShiftPhase
. The changes are:FrameChange ( < phase > )( < channel > ) -> ShiftPhase ( < phase > , < channel > ) FrameChangeInstruction ( FrameChange ( < phase > ), < channel > ) -> ShiftPhase ( < phase > , < channel > )
Until the deprecation period is over, the previous FrameChange syntax of calling a command on a channel will be supported:
ShiftPhase ( < phase > )( < channel > )
-
The
call
method ofSamplePulse
andParametricPulse
s have been deprecated. The migration is as follows:Pulse ( <* args > )( < channel > ) -> Play ( Pulse ( * args ), < channel > )
-
AcquireInstruction
has been deprecated and replaced byAcquire
. The changes are:Acquire ( < duration > )( <** channels > ) -> Acquire ( < duration > , <** channels > ) AcquireInstruction ( Acquire ( < duration > ), <** channels > ) -> Acquire ( < duration > , <** channels > )
Until the deprecation period is over, the previous Acquire syntax of calling the command on a channel will be supported:
Acquire ( < duration > )( <** channels > )
Bug Fixes¶
-
The
BarrierBeforeFinalMeasurements
transpiler pass, included in the preset transpiler levels when targeting a physical device, previously inserted a barrier across only measured qubits. In some cases, this allowed the transpiler to insert a swap after a measure operation, rendering the circuit invalid for current devices. The pass has been updated so that the inserted barrier will span all qubits on the device. Fixes #3937 -
When extending a
QuantumCircuit
instance (extendee) with another circuit (extension), the circuit is taken via reference. If a circuit is extended with itself that leads to an infinite loop as extendee and extension are the same. This bug has been resolved by copying the extension if it is the same object as the extendee. Fixes #3811 -
Fixes a case in
qiskit.result.Result.get_counts()
, where the results for an expirement could not be referenced if the experiment was initialized as a Schedule without a name. Fixes #2753 -
Previously, replacing
Parameter
objects in a circuit with new Parameter objects prior to decomposing a circuit would result in the substituted values not correctly being substituted into the decomposed gates. This has been resolved such that binding and decomposition may occur in any order. -
The matplotlib output backend for the
qiskit.visualization.circuit_drawer()
function andqiskit.circuit.QuantumCircuit.draw()
method drawer has been fixed to renderCU1Gate
gates correctly. Fixes #3684 -
A bug in
qiskit.circuit.QuantumCircuit.from_qasm_str()
andqiskit.circuit.QuantumCircuit.from_qasm_file()
when loading QASM with custom gates defined has been fixed. Now, loading this QASM:OPENQASM 2.0 ; include "qelib1.inc" ; gate rinv q { sdg q ; h q ; sdg q ; h q ; } qreg q [ 1 ]; rinv q [ 0 ];
is equivalent to the following circuit:
rinv_q = QuantumRegister ( 1 , name = 'q' ) rinv_gate = QuantumCircuit ( rinv_q , name = 'rinv' ) rinv_gate . sdg ( rinv_q ) rinv_gate . h ( rinv_q ) rinv_gate . sdg ( rinv_q ) rinv_gate . h ( rinv_q ) rinv = rinv_gate . to_instruction () qr = QuantumRegister ( 1 , name = 'q' ) expected = QuantumCircuit ( qr , name = 'circuit' ) expected . append ( rinv , [ qr [ 0 ]])
Fixes #1566
-
Allow quantum circuit Instructions to have list parameter values. This is used in Aer for expectation value snapshot parameters for example
params = [[1.0, 'I'], [1.0, 'X']]]
for \(\langle I + X\rangle\). -
Previously, for circuits containing composite gates (those created via
qiskit.circuit.QuantumCircuit.to_gate()
orqiskit.circuit.QuantumCircuit.to_instruction()
or their corresponding converters), attempting to bind the circuit more than once would result in only the first bind value being applied to all circuits when transpiled. This has been resolved so that the values provided for subsequent binds are correctly respected.
Other Notes¶
-
The qasm and pulse qobj classes:
-
QasmQobjInstruction
-
QobjExperimentHeader
-
QasmQobjExperimentConfig
-
QasmQobjExperiment
-
QasmQobjConfig
-
QobjHeader
-
PulseQobjInstruction
-
PulseQobjExperimentConfig
-
PulseQobjExperiment
-
PulseQobjConfig
-
QobjMeasurementOption
-
PulseLibraryItem
-
QasmQobjInstruction
-
QasmQobjExperimentConfig
-
QasmQobjExperiment
-
QasmQobjConfig
-
QasmQobj
-
PulseQobj
from
qiskit.qobj
have all been reimplemented without using the marsmallow library. These new implementations are designed to be drop-in replacement (except for as noted in the upgrade release notes) but specifics inherited from marshmallow may not work. Please file issues for any incompatibilities found. -
Aer 0.5.0¶
Added¶
Add support for terra diagonal gate
Add support for parameterized qobj
Fixed¶
Added postfix for linux on Raspberry Pi
Handle numpy array inputs from qobj
Ignis 0.3.0¶
Added¶
-
API documentation
-
CNOT-Dihedral randomized benchmarking
-
Accreditation module for output accrediation of noisy devices
-
Pulse calibrations for single qubits
-
Pulse Discriminator
-
Entanglement verification circuits
-
Gateset tomography for single-qubit gate sets
-
Adds randomized benchmarking utility functions
calculate_1q_epg
,calculate_2q_epg
functions to calculate 1 and 2-qubit error per gate from error per Clifford -
Adds randomized benchmarking utility functions
calculate_1q_epc
,calculate_2q_epc
for calculating 1 and 2-qubit error per Clifford from error per gate
Changed¶
-
Support integer labels for qubits in tomography
-
Support integer labels for measurement error mitigation
Deprecated¶
-
Deprecates
twoQ_clifford_error
function. Usecalculate_2q_epc
instead. -
Python 3.5 support in qiskit-ignis is deprecated. Support will be removed on the upstream python community's end of life date for the version, which is 09/13/2020.
IBM Q Provider 0.6.0¶
No Change
Qiskit 0.17.0¶
IBM Q Provider 0.6.0¶
New Features¶
-
There are three new exceptions:
VisualizationError
,VisualizationValueError
, andVisualizationTypeError
. These are now used in the visualization modules when an exception is raised. -
You can now set the logging level and specify a log file using the environment variables
QSIKIT_IBMQ_PROVIDER_LOG_LEVEL
andQISKIT_IBMQ_PROVIDER_LOG_FILE
, respectively. Note that the name of the logger isqiskit.providers.ibmq
. -
qiskit.providers.ibmq.job.IBMQJob
now has a new methodscheduling_mode()
that returns the scheduling mode the job is in. -
IQX-related tutorials that used to be in
qiskit-iqx-tutorials
are now inqiskit-ibmq-provider
.
Qiskit 0.16.0¶
IBM Q Provider 0.5.0¶
New Features¶
-
Some of the visualization and Jupyter tools, including gate/error map and backend information, have been moved from
qiskit-terra
toqiskit-ibmq-provider
. They are now under theqiskit.providers.ibmq.jupyter
andqiskit.providers.ibmq.visualization
. In addition, you can now use%iqx_dashboard
to get a dashboard that provides both job and backend information.
Changed¶
-
JSON schema validation is no longer run by default on Qobj objects passed to
qiskit.providers.ibmq.IBMQBackend.run()
. This significantly speeds up the execution of the run() method. Qobj objects are still validated on the server side, and invalid Qobjs will continue to raise exceptions. To force local validation, setvalidate_qobj=True
when you invokerun()
.
Qiskit 0.15.0¶
Terra 0.12.0¶
Prelude¶
The 0.12.0 release includes several new features and bug fixes. The biggest change for this release is the addition of support for parametric pulses to OpenPulse. These are Pulse commands which take parameters rather than sample points to describe a pulse. 0.12.0 is also the first release to include support for Python 3.8. It also marks the beginning of the deprecation for Python 3.5 support, which will be removed when the upstream community stops supporting it.
New Features¶
-
The pass
qiskit.transpiler.passes.CSPLayout
was extended with two new parameters:call_limit
andtime_limit
. These options allow limiting how long the pass will run. The optioncall_limit
limits the number of times that the recursive function in the backtracking solver may be called. Similarly,time_limit
limits how long (in seconds) the solver will be allowed to run. The defaults are1000
calls and10
seconds respectively. -
qiskit.pulse.Acquire
can now be applied to a single qubit. This makes pulse programming more consistent and easier to reason about, as now all operations apply to a single channel. For example:acquire = Acquire ( duration = 10 ) schedule = Schedule () schedule . insert ( 60 , acquire ( AcquireChannel ( 0 ), MemorySlot ( 0 ), RegisterSlot ( 0 ))) schedule . insert ( 60 , acquire ( AcquireChannel ( 1 ), MemorySlot ( 1 ), RegisterSlot ( 1 )))
-
A new method
qiskit.transpiler.CouplingMap.draw()
was added toqiskit.transpiler.CouplingMap
to generate a graphviz image from the coupling map graph. For example:from qiskit.transpiler import CouplingMap coupling_map = CouplingMap ( [[ 0 , 1 ], [ 1 , 0 ], [ 1 , 2 ], [ 1 , 3 ], [ 2 , 1 ], [ 3 , 1 ], [ 3 , 4 ], [ 4 , 3 ]]) coupling_map . draw ()
-
Parametric pulses have been added to OpenPulse. These are pulse commands which are parameterized and understood by the backend. Arbitrary pulse shapes are still supported by the SamplePulse Command. The new supported pulse classes are:
-
qiskit.pulse.ConstantPulse
-
qiskit.pulse.Drag
-
qiskit.pulse.Gaussian
-
qiskit.pulse.GaussianSquare
They can be used like any other Pulse command. An example:
from qiskit.pulse import ( Schedule , Gaussian , Drag , ConstantPulse , GaussianSquare ) sched = Schedule ( name = 'parametric_demo' ) sched += Gaussian ( duration = 25 , sigma = 4 , amp = 0.5 j )( DriveChannel ( 0 )) sched += Drag ( duration = 25 , amp = 0.1 , sigma = 5 , beta = 4 )( DriveChannel ( 1 )) sched += ConstantPulse ( duration = 25 , amp = 0.3 + 0.1 j )( DriveChannel ( 1 )) sched += GaussianSquare ( duration = 1500 , amp = 0.2 , sigma = 8 , width = 140 )( MeasureChannel ( 0 )) << sched . duration
The resulting schedule will be similar to a SamplePulse schedule built using
qiskit.pulse.pulse_lib
, however, waveform sampling will be performed by the backend. The methodqiskit.pulse.Schedule.draw()
can still be used as usual. However, the command will be converted to aSamplePulse
with theqiskit.pulse.ParametricPulse.get_sample_pulse()
method, so the pulse shown may not sample the continuous function the same way that the backend will.This feature can be used to construct Pulse programs for any backend, but the pulses will be converted to
SamplePulse
objects if the backend does not support parametric pulses. Backends which support them will have the following new attribute:backend . configuration () . parametric_pulses : List [ str ] # e.g. ['gaussian', 'drag', 'constant']
Note that the backend does not need to support all of the parametric pulses defined in Qiskit.
When the backend supports parametric pulses, and the Pulse schedule is built with them, the assembled Qobj is significantly smaller. The size of a PulseQobj built entirely with parametric pulses is dependent only on the number of instructions, whereas the size of a PulseQobj built otherwise will grow with the duration of the instructions (since every sample must be specified with a value).
-
-
Added utility functions,
qiskit.scheduler.measure()
andqiskit.scheduler.measure_all()
to qiskit.scheduler module. These functions return aqiskit.pulse.Schedule
object which measures qubits using OpenPulse. For example:from qiskit.scheduler import measure , measure_all measure_q0_schedule = measure ( qubits = [ 0 ], backend = backend ) measure_all_schedule = measure_all ( backend ) measure_custom_schedule = measure ( qubits = [ 0 ], inst_map = backend . defaults () . instruction_schedule_map , meas_map = [[ 0 ]], qubit_mem_slots = { 0 : 1 })
-
Pulse
qiskit.pulse.Schedule
objects now have better representations that for simple schedules should be valid Python expressions. -
The
qiskit.circuit.QuantumCircuit
methodsqiskit.circuit.QuantumCircuit.measure_active()
,qiskit.circuit.QuantumCircuit.measure_all()
, andqiskit.circuit.QuantumCircuit.remove_final_measurements()
now have an addition kwarginplace
. Wheninplace
is set toFalse
the function will return a modified copy of the circuit. This is different from the default behavior which will modify the circuit object in-place and return nothing. -
Several new constructor methods were added to the
qiskit.transpiler.CouplingMap
class for building objects with basic qubit coupling graphs. The new constructor methods are:-
qiskit.transpiler.CouplingMap.from_full()
-
qiskit.transpiler.CouplingMap.from_line()
-
qiskit.transpiler.CouplingMap.from_ring()
-
qiskit.transpiler.CouplingMap.from_grid()
For example, to use the new constructors to get a coupling map of 5 qubits connected in a linear chain you can now run:
from qiskit.transpiler import CouplingMap coupling_map = CouplingMap . from_line ( 5 ) coupling_map . draw ()
-
-
Introduced a new pass
qiskit.transpiler.passes.CrosstalkAdaptiveSchedule
. This pass aims to reduce the impact of crosstalk noise on a program. It uses crosstalk characterization data from the backend to schedule gates. When a pair of gates has high crosstalk, they get serialized using a barrier. Naive serialization is harmful because it incurs decoherence errors. Hence, this pass uses a SMT optimization approach to compute a schedule which minimizes the impact of crosstalk as well as decoherence errors.The pass takes as input a circuit which is already transpiled onto the backend i.e., the circuit is expressed in terms of physical qubits and swap gates have been inserted and decomposed into CNOTs if required. Using this circuit and crosstalk characterization data, a Z3 optimization is used to construct a new scheduled circuit as output.
To use the pass on a circuit circ:
dag = circuit_to_dag ( circ ) pass_ = CrosstalkAdaptiveSchedule ( backend_prop , crosstalk_prop ) scheduled_dag = pass_ . run ( dag ) scheduled_circ = dag_to_circuit ( scheduled_dag )
backend_prop
is aqiskit.providers.models.BackendProperties
object for the target backend.crosstalk_prop
is a dict which specifies conditional error rates. For two gatesg1
andg2
,crosstalk_prop[g1][g2]
specifies the conditional error rate ofg1
wheng1
andg2
are executed simultaneously. A method for generatingcrosstalk_prop
will be added in a future release of qiskit-ignis. Until then you'll either have to already know the crosstalk properties of your device, or manually write your own device characterization experiments. -
In the preset pass manager for optimization level 1,
qiskit.transpiler.preset_passmanagers.level_1_pass_manager()
ifqiskit.transpiler.passes.TrivialLayout
layout pass is not a perfect match for a particular circuit, thenqiskit.transpiler.passes.DenseLayout
layout pass is used instead. -
Added a new abstract method
qiskit.quantum_info.Operator.dot()
to the abstractBaseOperator
class, so it is included for all implementations of that abstract class, includingqiskit.quantum_info.Operator
andQuantumChannel
(e.g.,qiskit.quantum_info.Choi
) objects. This method returns the right operator multiplicationa.dot(b)
\(= a \cdot b\). This is equivalent to calling the operatorqiskit.quantum_info.Operator.compose()
method with the kwargfront
set toTrue
. -
Added
qiskit.quantum_info.average_gate_fidelity()
andqiskit.quantum_info.gate_error()
functions to theqiskit.quantum_info
module for working withqiskit.quantum_info.Operator
andQuantumChannel
(e.g.,qiskit.quantum_info.Choi
) objects. -
Added the
qiskit.quantum_info.partial_trace()
function to theqiskit.quantum_info
that works withqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
quantum state classes. For example:from qiskit.quantum_info.states import Statevector from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.states import partial_trace psi = Statevector . from_label ( '10+' ) partial_trace ( psi , [ 0 , 1 ]) rho = DensityMatrix . from_label ( '10+' ) partial_trace ( rho , [ 0 , 1 ])
-
When
qiskit.circuit.QuantumCircuit.draw()
orqiskit.visualization.circuit_drawer()
is called with thewith_layout
kwarg set True (the default) the output visualization will now display the physical qubits as integers to clearly distinguish them from the virtual qubits.For Example:
from qiskit import QuantumCircuit from qiskit import transpile from qiskit.test.mock import FakeVigo qc = QuantumCircuit ( 3 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc . cx ( 0 , 2 ) transpiled_qc = transpile ( qc , FakeVigo ()) transpiled_qc . draw ( output = 'mpl' )
-
Added new state measure functions to the
qiskit.quantum_info
module:qiskit.quantum_info.entropy()
,qiskit.quantum_info.mutual_information()
,qiskit.quantum_info.concurrence()
, andqiskit.quantum_info.entanglement_of_formation()
. These functions work with theqiskit.quantum_info.Statevector
andqiskit.quantum_info.DensityMatrix
classes. -
The decomposition methods for single-qubit gates in
qiskit.quantum_info.synthesis.one_qubit_decompose.OneQubitEulerDecomposer
have been expanded to now also include the'ZXZ'
basis, characterized by three rotations about the Z,X,Z axis. This now means that a general 2x2 Operator can be decomposed into following bases:U3
,U1X
,ZYZ
,ZXZ
,XYX
,ZXZ
.
Known Issues¶
-
Running functions that use
qiskit.tools.parallel_map()
(for exampleqiskit.execute.execute()
,qiskit.compiler.transpile()
, andqiskit.transpiler.PassManager.run()
) may not work when called from a script running outside of aif __name__ == '__main__':
block when using Python 3.8 on MacOS. Other environments are unaffected by this issue. This is due to changes in how parallel processes are launched by Python 3.8 on MacOS. IfRuntimeError
orAttributeError
are raised by scripts that are directly callingparallel_map()
or when calling a function that uses it internally with Python 3.8 on MacOS embedding the script calls insideif __name__ == '__main__':
should workaround the issue. For example:from qiskit import QuantumCircuit , QiskitError from qiskit import execute , BasicAer qc1 = QuantumCircuit ( 2 , 2 ) qc1 . h ( 0 ) qc1 . cx ( 0 , 1 ) qc1 . measure ([ 0 , 1 ], [ 0 , 1 ]) # making another circuit: superpositions qc2 = QuantumCircuit ( 2 , 2 ) qc2 . h ([ 0 , 1 ]) qc2 . measure ([ 0 , 1 ], [ 0 , 1 ]) execute ([ qc1 , qc2 ], BasicAer . get_backend ( 'qasm_simulator' ))
should be changed to:
from qiskit import QuantumCircuit , QiskitError from qiskit import execute , BasicAer def main (): qc1 = QuantumCircuit ( 2 , 2 ) qc1 . h ( 0 ) qc1 . cx ( 0 , 1 ) qc1 . measure ([ 0 , 1 ], [ 0 , 1 ]) # making another circuit: superpositions qc2 = QuantumCircuit ( 2 , 2 ) qc2 . h ([ 0 , 1 ]) qc2 . measure ([ 0 , 1 ], [ 0 , 1 ]) execute ([ qc1 , qc2 ], BasicAer . get_backend ( 'qasm_simulator' )) if __name__ == '__main__' : main ()
if errors are encountered with Python 3.8 on MacOS.
Upgrade Notes¶
-
The value of the
rep_time
parameter for Pulse backend's configuration object is now in units of seconds, not microseconds. The first time aPulseBackendConfiguration
object is initialized it will raise a single warning to the user to indicate this. -
The
rep_time
argument forqiskit.compiler.assemble()
now takes in a value in units of seconds, not microseconds. This was done to make the units with everything else in pulse. If you were passing in a value forrep_time
ensure that you update the value to account for this change. -
The value of the
base_gate
property ofqiskit.circuit.ControlledGate
objects has been changed from the class of the base gate to an instance of the class of the base gate. -
The
base_gate_name
property ofqiskit.circuit.ControlledGate
has been removed; you can get the name of the base gate by accessingbase_gate.name
on the object. For example:from qiskit import QuantumCircuit from qiskit.extensions import HGate qc = QuantumCircuit ( 3 ) cch_gate = HGate () . control ( 2 ) base_gate_name = cch_gate . base_gate . name
-
Changed
qiskit.quantum_info.Operator
magic methods so that__mul__
(which gets executed by python's multiplication operation, if the left hand side of the operation has it defined) implements right matrix multiplication (i.e.qiskit.quantum_info.Operator.dot()
), and__rmul__
(which gets executed by python's multiplication operation from the right hand side of the operation if the left does not have__mul__
defined) implements scalar multiplication (i.e.qiskit.quantum_info.Operator.multiply()
). Previously both methods implemented scalar multiplciation. -
The second argument of the
qiskit.quantum_info.process_fidelity()
function,target
, is now optional. If a target unitary is not specified, then process fidelity of the input channel with the identity operator will be returned. -
qiskit.compiler.assemble()
will now respect the configuredmax_shots
value for a backend. If a value for theshots
kwarg is specified that exceed the max shots set in the backend configuration the function will now raise aQiskitError
exception. Additionally, if no shots argument is provided the default value is either 1024 (the previous behavior) ormax_shots
from the backend, whichever is lower.
Deprecation Notes¶
-
Methods for adding gates to a
qiskit.circuit.QuantumCircuit
with abbreviated keyword arguments (e.g.ctl
,tgt
) have had their keyword arguments renamed to be more descriptive (e.g.control_qubit
,target_qubit
). The old names have been deprecated. A table including the old and new calling signatures for theQuantumCircuit
methods is included below.Table 5 New signatures for QuantumCircuit
gate methods¶Instruction Type
Former Signature
New Signature
qiskit.extensions.HGate
qc.h(q)
qc.h(qubit)
qiskit.extensions.CHGate
qc.ch(ctl, tgt)
qc.ch((control_qubit, target_qubit))
qiskit.extensions.IdGate
qc.iden(q)
qc.iden(qubit)
qiskit.extensions.RGate
qc.iden(q)
qc.iden(qubit)
qiskit.extensions.RGate
qc.r(theta, phi, q)
qc.r(theta, phi, qubit)
qiskit.extensions.RXGate
qc.rx(theta, q)
qc.rx(theta, qubit)
qiskit.extensions.CrxGate
qc.crx(theta, ctl, tgt)
qc.crx(theta, control_qubit, target_qubit)
qiskit.extensions.RYGate
qc.ry(theta, q)
qc.ry(theta, qubit)
qiskit.extensions.CryGate
qc.cry(theta, ctl, tgt)
qc.cry(theta, control_qubit, target_qubit)
qiskit.extensions.RZGate
qc.rz(phi, q)
qc.rz(phi, qubit)
qiskit.extensions.CrzGate
qc.crz(theta, ctl, tgt)
qc.crz(theta, control_qubit, target_qubit)
qiskit.extensions.SGate
qc.s(q)
qc.s(qubit)
qiskit.extensions.SdgGate
qc.sdg(q)
qc.sdg(qubit)
qiskit.extensions.FredkinGate
qc.cswap(ctl, tgt1, tgt2)
qc.cswap(control_qubit, target_qubit1, target_qubit2)
qiskit.extensions.TGate
qc.t(q)
qc.t(qubit)
qiskit.extensions.TdgGate
qc.tdg(q)
qc.tdg(qubit)
qiskit.extensions.U1Gate
qc.u1(theta, q)
qc.u1(theta, qubit)
qiskit.extensions.Cu1Gate
qc.cu1(theta, ctl, tgt)
qc.cu1(theta, control_qubit, target_qubit)
qiskit.extensions.U2Gate
qc.u2(phi, lam, q)
qc.u2(phi, lam, qubit)
qiskit.extensions.U3Gate
qc.u3(theta, phi, lam, q)
qc.u3(theta, phi, lam, qubit)
qiskit.extensions.Cu3Gate
qc.cu3(theta, phi, lam, ctl, tgt)
qc.cu3(theta, phi, lam, control_qubit, target_qubit)
qiskit.extensions.XGate
qc.x(q)
qc.x(qubit)
qiskit.extensions.CnotGate
qc.cx(ctl, tgt)
qc.cx(control_qubit, target_qubit)
qiskit.extensions.ToffoliGate
qc.ccx(ctl1, ctl2, tgt)
qc.ccx(control_qubit1, control_qubit2, target_qubit)
qiskit.extensions.YGate
qc.y(q)
qc.y(qubit)
qiskit.extensions.CyGate
qc.cy(ctl, tgt)
qc.cy(control_qubit, target_qubit)
qiskit.extensions.ZGate
qc.z(q)
qc.z(qubit)
qiskit.extensions.CzGate
qc.cz(ctl, tgt)
qc.cz(control_qubit, target_qubit)
-
Running
qiskit.pulse.Acquire
on multiple qubits has been deprecated and will be removed in a future release. Additionally, theqiskit.pulse.AcquireInstruction
parametersmem_slots
andreg_slots
have been deprecated. Insteadreg_slot
andmem_slot
should be used instead. -
The attribute of the
qiskit.providers.models.PulseDefaults
classcircuit_instruction_map
has been deprecated and will be removed in a future release. Instead you should use the new attributeinstruction_schedule_map
. This was done to match the type of the value of the attribute, which is anInstructionScheduleMap
. -
The
qiskit.pulse.PersistentValue
command is deprecated and will be removed in a future release. Similar functionality can be achieved with theqiskit.pulse.ConstantPulse
command (one of the new parametric pulses). Compare the following:from qiskit.pulse import Schedule , PersistentValue , ConstantPulse , \ DriveChannel # deprecated implementation sched_w_pv = Schedule () sched_w_pv += PersistentValue ( value = 0.5 )( DriveChannel ( 0 )) sched_w_pv += PersistentValue ( value = 0 )( DriveChannel ( 0 )) << 10 # preferred implementation sched_w_const = Schedule () sched_w_const += ConstantPulse ( duration = 10 , amp = 0.5 )( DriveChannel ( 0 ))
-
Python 3.5 support in qiskit-terra is deprecated. Support will be removed in the first release after the upstream Python community's end of life date for the version, which is 09/13/2020.
-
The
require_cptp
kwarg of theqiskit.quantum_info.process_fidelity()
function has been deprecated and will be removed in a future release. It is superseded by two separate kwargsrequire_cp
andrequire_tp
. -
Setting the
scale
parameter forqiskit.circuit.QuantumCircuit.draw()
andqiskit.visualization.circuit_drawer()
as the first positional argument is deprecated and will be removed in a future release. Instead you should usescale
as keyword argument. -
The
qiskit.tools.qi.qi
module is deprecated and will be removed in a future release. The legacy functions in the module have all been superseded by functions and classes in theqiskit.quantum_info
module. A table of the deprecated functions and their replacement are below:Table 6 qiskit.tools.qi.qi
replacements¶Deprecated
Replacement
qiskit.tools.partial_trace()
qiskit.quantum_info.partial_trace()
qiskit.tools.choi_to_pauli()
qiskit.quantum_info.Choi
andquantum_info.PTM
qiskit.tools.chop()
numpy.round
qiskit.tools.qi.qi.outer
numpy.outer
qiskit.tools.concurrence()
qiskit.quantum_info.concurrence()
qiskit.tools.shannon_entropy()
qiskit.quantum_info.shannon_entropy()
qiskit.tools.entropy()
qiskit.quantum_info.entropy()
qiskit.tools.mutual_information()
qiskit.quantum_info.mutual_information()
qiskit.tools.entanglement_of_formation()
qiskit.quantum_info.entanglement_of_formation()
qiskit.tools.is_pos_def()
quantum_info.operators.predicates.is_positive_semidefinite_matrix
-
The
qiskit.quantum_info.states.states
module is deprecated and will be removed in a future release. The legacy functions in the module have all been superseded by functions and classes in theqiskit.quantum_info
module.Table 7 qiskit.quantum_info.states.states
replacements¶Deprecated
Replacement
qiskit.quantum_info.states.states.basis_state
qiskit.quantum_info.Statevector.from_label()
qiskit.quantum_info.states.states.projector
qiskit.quantum_info.DensityMatrix
-
The
scaling
parameter of thedraw()
method for theSchedule
andPulse
objects was deprecated and will be removed in a future release. Instead the newscale
parameter should be used. This was done to have a consistent argument between pulse and circuit drawings. For example:#The consistency in parameters is seen below #For circuits circuit = QuantumCircuit () circuit . draw ( scale = 0.2 ) #For pulses pulse = SamplePulse () pulse . draw ( scale = 0.2 ) #For schedules schedule = Schedule () schedule . draw ( scale = 0.2 )
Bug Fixes¶
-
Previously, calling
qiskit.circuit.QuantumCircuit.bind_parameters()
prior to decomposing a circuit would result in the bound values not being correctly substituted into the decomposed gates. This has been resolved such that binding and decomposition may occur in any order. Fixes issue #2482 and issue #3509 -
The
Collect2qBlocks
pass had previously not considered classical conditions when determining whether to include a gate within an existing block. In some cases, this resulted in classical conditions being lost when transpiling withoptimization_level=3
. This has been resolved so that classically conditioned gates are never included in a block. Fixes issue #3215 -
All the output types for the circuit drawers in
qiskit.circuit.QuantumCircuit.draw()
andqiskit.visualization.circuit_drawer()
have fixed and/or improved support for drawing controlled custom gates. Fixes issue #3546, issue #3763, and issue #3764 -
Explanation and examples have been added to documentation for the
qiskit.circuit.QuantumCircuit
methods for adding gates:qiskit.circuit.QuantumCircuit.ccx()
,qiskit.circuit.QuantumCircuit.ch()
,qiskit.circuit.QuantumCircuit.crz()
,qiskit.circuit.QuantumCircuit.cswap()
,qiskit.circuit.QuantumCircuit.cu1()
,qiskit.circuit.QuantumCircuit.cu3()
,qiskit.circuit.QuantumCircuit.cx()
,qiskit.circuit.QuantumCircuit.cy()
,qiskit.circuit.QuantumCircuit.cz()
,qiskit.circuit.QuantumCircuit.h()
,qiskit.circuit.QuantumCircuit.iden()
,qiskit.circuit.QuantumCircuit.rx()
,qiskit.circuit.QuantumCircuit.ry()
,qiskit.circuit.QuantumCircuit.rz()
,qiskit.circuit.QuantumCircuit.s()
,qiskit.circuit.QuantumCircuit.sdg()
,qiskit.circuit.QuantumCircuit.swap()
,qiskit.circuit.QuantumCircuit.t()
,qiskit.circuit.QuantumCircuit.tdg()
,qiskit.circuit.QuantumCircuit.u1()
,qiskit.circuit.QuantumCircuit.u2()
,qiskit.circuit.QuantumCircuit.u3()
,qiskit.circuit.QuantumCircuit.x()
,qiskit.circuit.QuantumCircuit.y()
,qiskit.circuit.QuantumCircuit.z()
. Fixes issue #3400 -
Fixes for handling of complex number parameter in circuit visualization. Fixes issue #3640
Other Notes¶
-
The transpiler passes in the
qiskit.transpiler.passes
directory have been organized into subdirectories to better categorize them by functionality. They are still all accessible under theqiskit.transpiler.passes
namespace.
Aer 0.4.0¶
Added¶
Added
NoiseModel.from_backend
for building a basic device noise model for an IBMQ backend (#569)Added multi-GPU enabled simulation methods to the
QasmSimulator
,StatevectorSimulator
, andUnitarySimulator
. The qasm simulator has gpu version of the density matrix and statevector methods and can be accessed using"method": "density_matrix_gpu"
or"method": "statevector_gpu"
inbackend_options
. The statevector simulator gpu method can be accessed using"method": "statevector_gpu"
. The unitary simulator GPU method can be accessed using"method": "unitary_gpu"
. These backends use CUDA and require an NVidia GPU.(#544)Added
PulseSimulator
backend (#542)Added
PulseSystemModel
andHamiltonianModel
classes to represent models to be used inPulseSimulator
(#496, #493)Added
duffing_model_generators
to generatePulseSystemModel
objects from a list of parameters (#516)Migrated ODE function solver to C++ (#442, #350)
Added high level pulse simulator tests (#379)
CMake BLAS_LIB_PATH flag to set path to look for BLAS lib (#543)
Changed¶
Changed the structure of the
src
directory to organise simulator source code. Simulator controller headers were moved tosrc/controllers
and simulator method State headers are insrc/simulators
(#544)Moved the location of several functions (#568): * Moved contents of
qiskit.provider.aer.noise.errors
into theqiskit.providers.noise
module * Moved contents ofqiskit.provider.aer.noise.utils
into theqiskit.provider.aer.utils
module.Enabled optimization to aggregate consecutive gates in a circuit (fusion) by default (#579).
Deprecated¶
Deprecated
utils.qobj_utils
functions (#568)Deprecated
qiskit.providers.aer.noise.device.basic_device_noise_model
. It is superseded by theNoiseModel.from_backend
method (#569)
Removed¶
Removed
NoiseModel.as_dict
,QuantumError.as_dict
,ReadoutError.as_dict
, andQuantumError.kron
methods that were deprecated in 0.3 (#568).
IBM Q Provider 0.4.6¶
Added¶
-
Several new methods were added to
IBMQBackend
:-
wait_for_final_state()
blocks until the job finishes. It takes a callback function that it will invoke after every query to provide feedback. -
active_jobs()
returns the jobs submitted to a backend that are currently in an unfinished status. -
job_limit()
returns the job limit for a backend. -
remaining_jobs_count()
returns the number of jobs that you can submit to the backend before job limit is reached.
-
-
QueueInfo
now has a newformat()
method that returns a formatted string of the queue information. -
IBMQJob
now has three new methods:done()
,running()
, andcancelled()
that are used to indicate job status. -
qiskit.providers.ibmq.ibmqbackend.IBMQBackend.run()
now accepts an optional job_tags parameter. If specified, the job_tags are assigned to the job, which can later be used as a filter inqiskit.providers.ibmq.ibmqbackend.IBMQBackend.jobs()
. -
IBMQJobManager
now has a new methodretrieve_job_set()
that allows you to retrieve a previously submitted job set using the job set ID.
Changed¶
-
The
Exception
hierarchy has been refined with more specialized classes. You can, however, continue to catch their parent exceptions (such asIBMQAccountError
). Also, the exception classIBMQApiUrlError
has been replaced byIBMQAccountCredentialsInvalidUrl
andIBMQAccountCredentialsInvalidToken
.
Deprecated¶
-
The use of proxy urls without a protocol (e.g.
http://
) is deprecated due to recent Python changes.
Qiskit 0.14.0¶
Terra 0.11.0¶
Prelude¶
The 0.11.0 release includes several new features and bug fixes. The biggest change for this release is the addition of the pulse scheduler. This allows users to define their quantum program as a QuantumCircuit
and then map it to the underlying pulse instructions that will control the quantum hardware to implement the circuit.
New Features¶
-
Added 5 new commands to easily retrieve user-specific data from
BackendProperties
:gate_property
,gate_error
,gate_length
,qubit_property
,t1
,t2
,readout_error
andfrequency
. They return the specific values of backend properties. For example:from qiskit.test.mock import FakeOurense backend = FakeOurense () properties = backend . properties () gate_property = properties . gate_property ( 'u1' ) gate_error = properties . gate_error ( 'u1' , 0 ) gate_length = properties . gate_length ( 'u1' , 0 ) qubit_0_property = properties . qubit_property ( 0 ) t1_time_0 = properties . t1 ( 0 ) t2_time_0 = properties . t2 ( 0 ) readout_error_0 = properties . readout_error ( 0 ) frequency_0 = properties . frequency ( 0 )
-
Added method
Instruction.is_parameterized()
to check if an instruction object is parameterized. This method returnsTrue
if and only if instruction has aParameterExpression
orParameter
object for one of its params. -
Added a new analysis pass
Layout2qDistance
. This pass allows to "score" a layout selection, onceproperty_set['layout']
is set. The score will be the sum of distances for each two-qubit gate in the circuit, when they are not directly connected. This scoring does not consider direction in the coupling map. The lower the number, the better the layout selection is.For example, consider a linear coupling map
[0]--[2]--[1]
and the following circuit:qr = QuantumRegister ( 2 , 'qr' ) circuit = QuantumCircuit ( qr ) circuit . cx ( qr [ 0 ], qr [ 1 ])
If the layout is
{qr[0]:0, qr[1]:1}
,Layout2qDistance
will setproperty_set['layout_score'] = 1
. If the layout is{qr[0]:0, qr[1]:2}
, then the result isproperty_set['layout_score'] = 0
. The lower the score, the better. -
Added
qiskit.QuantumCircuit.cnot
as an alias for thecx
method ofQuantumCircuit
. The namescnot
andcx
are often used interchangeably now the cx method can be called with either name. -
Added
qiskit.QuantumCircuit.toffoli
as an alias for theccx
method ofQuantumCircuit
. The namestoffoli
andccx
are often used interchangeably now the ccx method can be called with either name. -
Added
qiskit.QuantumCircuit.fredkin
as an alias for thecswap
method ofQuantumCircuit
. The namesfredkin
andcswap
are often used interchangeably now the cswap method can be called with either name. -
The
latex
output mode forqiskit.visualization.circuit_drawer()
and theqiskit.circuit.QuantumCircuit.draw()
method now has a mode to passthrough raw latex from gate labels and parameters. The syntax for doing this mirrors matplotlib's mathtext mode syntax. Any portion of a label string between a pair of '$' characters will be treated as raw latex and passed directly into the generated output latex. This can be leveraged to add more advanced formatting to circuit diagrams generated with the latex drawer.Prior to this release all gate labels were run through a utf8 -> latex conversion to make sure that the output latex would compile the string as expected. This is still what happens for all portions of a label outside the '$' pair. Also if you want to use a dollar sign in your label make sure you escape it in the label string (ie
'\$'
).You can mix and match this passthrough with the utf8 -> latex conversion to create the exact label you want, for example:
from qiskit import circuit circ = circuit . QuantumCircuit ( 2 ) circ . h ([ 0 , 1 ]) circ . append ( circuit . Gate ( name = 'α_gate' , num_qubits = 1 , params = [ 0 ]), [ 0 ]) circ . append ( circuit . Gate ( name = 'α_gate$_2$' , num_qubits = 1 , params = [ 0 ]), [ 1 ]) circ . append ( circuit . Gate ( name = '\$α\$_gate' , num_qubits = 1 , params = [ 0 ]), [ 1 ]) circ . draw ( output = 'latex' )
will now render the first custom gate's label as
α_gate
, the second will beα_gate
with a 2 subscript, and the last custom gate's label will be$α$_gate
. -
Add
ControlledGate
class for representing controlled gates. Controlled gate instances are created with thecontrol(n)
method ofGate
objects wheren
represents the number of controls. The control qubits come before the controlled qubits in the new gate. For example:from qiskit import QuantumCircuit from qiskit.extensions import HGate hgate = HGate () circ = QuantumCircuit ( 4 ) circ . append ( hgate . control ( 3 ), [ 0 , 1 , 2 , 3 ]) print ( circ )
generates:
q_0: |0>──■── │ q_1: |0>──■── │ q_2: |0>──■── ┌─┴─┐ q_3: |0>┤ H ├ └───┘
-
Allowed values of
meas_level
parameters and fields can now be a member from the IntEnum classqiskit.qobj.utils.MeasLevel
. This can be used when callingexecute
(or anywhere elsemeas_level
is specified) with a pulse experiment. For example:from qiskit import QuantumCircuit , transpile , schedule , execute from qiskit.test.mock import FakeOpenPulse2Q from qiskit.qobj.utils import MeasLevel , MeasReturnType backend = FakeOpenPulse2Q () qc = QuantumCircuit ( 2 , 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc_transpiled = transpile ( qc , backend ) sched = schedule ( qc_transpiled , backend ) execute ( sched , backend , meas_level = MeasLevel . CLASSIFIED )
In this above example,
meas_level=MeasLevel.CLASSIFIED
andmeas_level=2
can be used interchangably now. -
A new layout selector based on constraint solving is included. CSPLayout models the problem of finding a layout as a constraint problem and uses recursive backtracking to solve it.
cmap16 = CouplingMap ( FakeRueschlikon () . configuration () . coupling_map ) qr = QuantumRegister ( 5 , 'q' ) circuit = QuantumCircuit ( qr ) circuit . cx ( qr [ 0 ], qr [ 1 ]) circuit . cx ( qr [ 0 ], qr [ 2 ]) circuit . cx ( qr [ 0 ], qr [ 3 ]) pm = PassManager ( CSPLayout ( cmap16 )) circuit_after = pm . run ( circuit ) print ( pm . property_set [ 'layout' ])
Layout ({ 1 : Qubit ( QuantumRegister ( 5 , 'q' ), 1 ), 2 : Qubit ( QuantumRegister ( 5 , 'q' ), 0 ), 3 : Qubit ( QuantumRegister ( 5 , 'q' ), 3 ), 4 : Qubit ( QuantumRegister ( 5 , 'q' ), 4 ), 15 : Qubit ( QuantumRegister ( 5 , 'q' ), 2 ) })
The parameter
CSPLayout(...,strict_direction=True)
is more restrictive but it will guarantee there is no need of runningCXDirection
after.pm = PassManager ( CSPLayout ( cmap16 , strict_direction = True )) circuit_after = pm . run ( circuit ) print ( pm . property_set [ 'layout' ])
Layout ({ 8 : Qubit ( QuantumRegister ( 5 , 'q' ), 4 ), 11 : Qubit ( QuantumRegister ( 5 , 'q' ), 3 ), 5 : Qubit ( QuantumRegister ( 5 , 'q' ), 1 ), 6 : Qubit ( QuantumRegister ( 5 , 'q' ), 0 ), 7 : Qubit ( QuantumRegister ( 5 , 'q' ), 2 ) })
If the constraint system is not solvable, the layout property is not set.
circuit . cx ( qr [ 0 ], qr [ 4 ]) pm = PassManager ( CSPLayout ( cmap16 )) circuit_after = pm . run ( circuit ) print ( pm . property_set [ 'layout' ])
-
PulseBackendConfiguration (accessed normally as backend.configuration()) has been extended with useful methods to explore its data and the functionality that exists in PulseChannelSpec. PulseChannelSpec will be deprecated in the future. For example:
backend = provider . get_backend ( backend_name ) config = backend . configuration () q0_drive = config . drive ( 0 ) # or, DriveChannel(0) q0_meas = config . measure ( 0 ) # MeasureChannel(0) q0_acquire = config . acquire ( 0 ) # AcquireChannel(0) config . hamiltonian # Returns a dictionary with hamiltonian info config . sample_rate () # New method which returns 1 / dt
-
PulseDefaults
(accessed normally asbackend.defaults()
) has an attribute,circuit_instruction_map
which has the methods of CmdDef. The new circuit_instruction_map is anInstructionScheduleMap
object with three new functions beyond what CmdDef had:-
qubit_instructions(qubits) returns the operations defined for the qubits
-
assert_has(instruction, qubits) raises an error if the op isn't defined
-
remove(instruction, qubits) like pop, but doesn't require parameters
There are some differences from the CmdDef:
-
__init__
takes no arguments -
cmds
andcmd_qubits
are deprecated and replaced withinstructions
andqubits_with_instruction
Example:
backend = provider . get_backend ( backend_name ) inst_map = backend . defaults () . circuit_instruction_map qubit = inst_map . qubits_with_instruction ( 'u3' )[ 0 ] x_gate = inst_map . get ( 'u3' , qubit , P0 = np . pi , P1 = 0 , P2 = np . pi ) pulse_schedule = x_gate ( DriveChannel ( qubit ))
-
-
A new kwarg parameter,
show_framechange_channels
to optionally disable displaying channels with only framechange instructions in pulse visualizations was added to theqiskit.visualization.pulse_drawer()
function andqiskit.pulse.Schedule.draw()
method. When this new kwarg is set toFalse
the output pulse schedule visualization will not include any channels that only include frame changes.For example:
from qiskit.pulse import * from qiskit.pulse import library as pulse_lib gp0 = pulse_lib . gaussian ( duration = 20 , amp = 1.0 , sigma = 1.0 ) sched = Schedule () channel_a = DriveChannel ( 0 ) channel_b = DriveChannel ( 1 ) sched += Play ( gp0 , channel_a ) sched = sched . insert ( 60 , ShiftPhase ( - 1.57 , channel_a )) sched = sched . insert ( 30 , ShiftPhase ( - 1.50 , channel_b )) sched = sched . insert ( 70 , ShiftPhase ( 1.50 , channel_b )) sched . draw ( show_framechange_channels = False )
-
A new utility function
qiskit.result.marginal_counts()
is added which allows marginalization of the counts over some indices of interest. This is useful when more qubits are measured than needed, and one wishes to get the observation counts for some subset of them only. -
When
passmanager.run(...)
is invoked with more than one circuit, the transpilation of these circuits will run in parallel. -
PassManagers can now be sliced to create a new PassManager containing a subset of passes using the square bracket operator. This allow running or drawing a portion of the PassManager for easier testing and visualization. For example let's try to draw the first 3 passes of a PassManager pm, or run just the second pass on our circuit:
pm [ 0 : 4 ] . draw () circuit2 = pm [ 1 ] . run ( circuit )
Also now, PassManagers can be created by adding two PassManagers or by directly adding a pass/list of passes to a PassManager.
pm = pm1 [ 0 ] + pm2 [ 1 : 3 ] pm += [ setLayout , unroller ]
-
A basic
scheduler
module has now been added to Qiskit. The scheduler schedules an input transpiledQuantumCircuit
into a pulseSchedule
. The scheduler accepts as input aSchedule
and either a pulseBackend
, or aCmdDef
which relates circuitInstruction
objects on specific qubits to pulse Schedules and ameas_map
which determines which measurements must occur together.Scheduling example:
from qiskit import QuantumCircuit , transpile , schedule from qiskit.test.mock import FakeOpenPulse2Q backend = FakeOpenPulse2Q () qc = QuantumCircuit ( 2 , 2 ) qc . h ( 0 ) qc . cx ( 0 , 1 ) qc_transpiled = transpile ( qc , backend ) schedule ( qc_transpiled , backend )
The scheduler currently supports two scheduling policies, as_late_as_possible (
alap
) and as_soon_as_possible (asap
), which respectively schedule pulse instructions to occur as late as possible or as soon as possible across qubits in a circuit. The scheduling policy may be selected with the input argumentmethod
, for example:schedule ( qc_transpiled , backend , method = 'alap' )
It is easy to use a pulse
Schedule
within aQuantumCircuit
by mapping it to a custom circuit instruction such as a gate which may be used in aQuantumCircuit
. To do this, first, define the custom gate and then add an entry into theCmdDef
for the gate, for each qubit that the gate will be applied to. The gate can then be used in theQuantumCircuit
. At scheduling time the gate will be mapped to the underlying pulse schedule. Using this technique allows easy integration with preexisting qiskit modules such as Ignis.For example:
from qiskit import pulse , circuit , schedule from qiskit.pulse import pulse_lib custom_cmd_def = pulse . CmdDef () # create custom gate custom_gate = circuit . Gate ( name = 'custom_gate' , num_qubits = 1 , params = []) # define schedule for custom gate custom_schedule = pulse . Schedule () custom_schedule += pulse_lib . gaussian ( 20 , 1.0 , 10 )( pulse . DriveChannel ) # add schedule to custom gate with same name custom_cmd_def . add ( 'custom_gate' , ( 0 ,), custom_schedule ) # use custom gate in a circuit custom_qc = circuit . QuantumCircuit ( 1 ) custom_qc . append ( custom_gate , qargs = [ 0 ]) # schedule the custom gate schedule ( custom_qc , cmd_def = custom_cmd_def , meas_map = [[ 0 ]])
Known Issues¶
-
The feature for transpiling in parallel when
passmanager.run(...)
is invoked with more than one circuit is not supported under Windows. See #2988 for more details.
Upgrade Notes¶
-
The
qiskit.pulse.channels.SystemTopology
class was used as a helper class forPulseChannelSpec
. It has been removed since with the deprecation ofPulseChannelSpec
and changes toBackendConfiguration
make it unnecessary. -
The previously deprecated representation of qubits and classical bits as tuple, which was deprecated in the 0.9 release, has been removed. The use of
Qubit
andClbit
objects is the new way to represent qubits and classical bits. -
The previously deprecated representation of the basis set as single string has been removed. A list of strings is the new preferred way.
-
The method
BaseModel.as_dict
, which was deprecated in the 0.9 release, has been removed in favor of the methodBaseModel.to_dict
. -
In PulseDefaults (accessed normally as backend.defaults()),
qubit_freq_est
andmeas_freq_est
are now returned in Hz rather than GHz. This means the new return values are 1e9 * their previous value. -
dill was added as a requirement. This is needed to enable running
passmanager.run()
in parallel for more than one circuit. -
The previously deprecated gate
UBase
, which was deprecated in the 0.9 release, has been removed. The gateU3Gate
should be used instead. -
The previously deprecated gate
CXBase
, which was deprecated in the 0.9 release, has been removed. The gateCnotGate
should be used instead. -
The instruction
snapshot
used to implicitly convert thelabel
parameter to string. That conversion has been removed and an error is raised if a string is not provided. -
The previously deprecated gate
U0Gate
, which was deprecated in the 0.9 release, has been removed. The gateIdGate
should be used instead to insert delays.
Deprecation Notes¶
-
The
qiskit.pulse.CmdDef
class has been deprecated. Instead you should use theqiskit.pulse.InstructionScheduleMap
. TheInstructionScheduleMap
object for a pulse enabled system can be accessed atbackend.defaults().instruction_schedules
. -
PulseChannelSpec
is being deprecated. UseBackendConfiguration
instead. The backend configuration is accessed normally asbackend.configuration()
. The config has been extended with most of the functionality of PulseChannelSpec, with some modifications as follows, where 0 is an exemplary qubit index:pulse_spec . drives [ 0 ] -> config . drive ( 0 ) pulse_spec . measures [ 0 ] -> config . measure ( 0 ) pulse_spec . acquires [ 0 ] -> config . acquire ( 0 ) pulse_spec . controls [ 0 ] -> config . control ( 0 )
Now, if there is an attempt to get a channel for a qubit which does not exist for the device, a
BackendConfigurationError
will be raised with a helpful explanation.The methods
memoryslots
andregisterslots
of the PulseChannelSpec have not been migrated to the backend configuration. These classical resources are not restrained by the physical configuration of a backend system. Please instantiate them directly:pulse_spec . memoryslots [ 0 ] -> MemorySlot ( 0 ) pulse_spec . registerslots [ 0 ] -> RegisterSlot ( 0 )
The
qubits
method is not migrated to backend configuration. The result ofqubits
can be built as such:[ q for q in range ( backend . configuration () . n_qubits )]
-
Qubit
withinpulse.channels
has been deprecated. They should not be used. It is possible to obtain channel <=> qubit mappings through the BackendConfiguration (or backend.configuration()). -
The function
qiskit.visualization.circuit_drawer.qx_color_scheme()
has been deprecated. This function is no longer used internally and doesn't reflect the current IBM QX style. If you were using this function to generate a style dict locally you must save the output from it and use that dictionary directly. -
The Exception
TranspilerAccessError
has been deprecated. An alternative functionTranspilerError
can be used instead to provide the same functionality. This alternative function provides the exact same functionality but with greater generality. -
Buffers in Pulse are deprecated. If a nonzero buffer is supplied, a warning will be issued with a reminder to use a Delay instead. Other options would include adding samples to a pulse instruction which are (0.+0.j) or setting the start time of the next pulse to
schedule.duration + buffer
. -
Passing in
sympy.Basic
,sympy.Expr
andsympy.Matrix
types as instruction parameters are deprecated and will be removed in a future release. You'll need to convert the input to one of the supported types which are:-
int
-
float
-
complex
-
str
-
np.ndarray
-
Bug Fixes¶
-
The Collect2qBlocks and CommutationAnalysis passes in the transpiler had been unable to process circuits containing Parameterized gates, preventing Parameterized circuits from being transpiled at optimization_level 2 or above. These passes have been corrected to treat Parameterized gates as opaque.
-
The align_measures function had an issue where Measure stimulus pulses weren't properly aligned with Acquire pulses, resulting in an error. This has been fixed.
-
Uses of
numpy.random.seed
have been removed so that calls of qiskit functions do not affect results of future calls tonumpy.random
-
Fixed race condition occurring in the job monitor when
job.queue_position()
returnsNone
.None
is a valid return fromjob.queue_position()
. -
Backend support for
memory=True
now checked when that kwarg is passed.QiskitError
results if not supported. -
When transpiling without a coupling map, there were no check in the amount of qubits of the circuit to transpile. Now the transpile process checks that the backend has enough qubits to allocate the circuit.
Other Notes¶
-
The
qiskit.result.marginal_counts()
function replaces a similar utility function in qiskit-ignisqiskit.ignis.verification.tomography.marginal_counts()
, which will be deprecated in a future qiskit-ignis release. -
All sympy parameter output type support have been been removed (or deprecated as noted) from qiskit-terra. This includes sympy type parameters in
QuantumCircuit
objects, qasm ast nodes, orQobj
objects.
IBM Q Provider 0.4¶
Prelude¶
The 0.4.0 release is the first release that makes use of all the features of the new IBM Q API. In particular, the IBMQJob
class has been revamped in order to be able to retrieve more information from IBM Q, and a Job Manager class has been added for allowing a higher-level and more seamless usage of large or complex jobs. If you have not upgraded from the legacy IBM Q Experience or QConsole yet, please ensure to revisit the release notes for IBM Q Provider 0.3 (Qiskit 0.11) for more details on how to make the transition. The legacy accounts will no longer be supported as of this release.
New Features¶
Job modifications¶
The IBMQJob
class has been revised, and now mimics more closely to the contents of a remote job along with new features:
-
You can now assign a name to a job, by specifying
IBMQBackend.run(..., job_name='...')
when submitting a job. This name can be retrieved viaIBMQJob.name()
and can be used for filtering. -
Jobs can now be shared with other users at different levels (global, per hub, group or project) via an optional
job_share_level
parameter when submitting the job. -
IBMQJob
instances now have more attributes, reflecting the contents of the remote IBM Q jobs. This implies that new attributes introduced by the IBM Q API will automatically and immediately be available for use (for example,job.new_api_attribute
). The new attributes will be promoted to methods when they are considered stable (for example,job.name()
). -
.error_message()
returns more information on why a job failed. -
.queue_position()
accepts arefresh
parameter for forcing an update. -
.result()
accepts an optionalpartial
parameter, for returning partial results, if any, of jobs that failed. Be aware thatResult
methods, such asget_counts()
will raise an exception if applied on experiments that failed.
Please note that the changes include some low-level modifications of the class. If you were creating the instances manually, note that:
-
the signature of the constructor has changed to account for the new features.
-
the
.submit()
method can no longer be called directly, and jobs are expected to be submitted either via the synchronousIBMQBackend.run()
or via the Job Manager.
Job Manager¶
A new Job Manager ( IBMQJobManager
) has been introduced, as a higher-level mechanism for handling jobs composed of multiple circuits or pulse schedules. The Job Manager aims to provide a transparent interface, intelligently splitting the input into efficient units of work and taking full advantage of the different components. It will be expanded on upcoming versions, and become the recommended entry point for job submission.
Its .run()
method receives a list of circuits or pulse schedules, and returns a ManagedJobSet instance
, which can then be used to track the statuses and results of these jobs. For example:
from qiskit.providers.ibmq.managed import IBMQJobManager from qiskit.circuit.random import random_circuit from qiskit import IBMQ from qiskit.compiler import transpile provider = IBMQ . load_account () backend = provider . backends . ibmq_ourense circs = [] for _ in range ( 1000000 ): circs . append ( random_circuit ( 2 , 2 )) transpile ( circs , backend = backend ) # Farm out the jobs. jm = IBMQJobManager () job_set = jm . run ( circs , backend = backend , name = 'foo' ) job_set . statuses () # Gives a list of job statuses job_set . report () # Prints detailed job information results = job_set . results () counts = results . get_counts ( 5 ) # Returns data for experiment 5
provider.backends modifications¶
The provider.backends
member, which was previously a function that returned a list of backends, has been promoted to a service. This implies that it can be used both in the previous way, as a .backends()
method, and also as a .backends
attribute with expanded capabilities:
-
it contains the existing backends from that provider as attributes, which can be used for autocompletion. For example:
my_backend = provider . get_backend ( 'ibmq_qasm_simulator' )
is equivalent to:
my_backend = provider . backends . ibmq_qasm_simulator
-
the
provider.backends.jobs()
andprovider.backends.retrieve_job()
methods can be used for retrieving provider-wide jobs.
Other changes¶
-
The
backend.properties()
function now accepts an optionaldatetime
parameter. If specified, the function returns the backend properties closest to, but older than, the specified datetime filter. -
Some
warnings
have been toned down tologger.warning
messages.
Qiskit 0.13.0¶
Terra 0.10.0¶
Prelude¶
The 0.10.0 release includes several new features and bug fixes. The biggest change for this release is the addition of initial support for using Qiskit with trapped ion trap backends.
New Features¶
-
Introduced new methods in
QuantumCircuit
which allows the seamless adding or removing of measurements at the end of a circuit.-
measure_all()
-
Adds a
barrier
followed by ameasure
operation to all qubits in the circuit. Creates aClassicalRegister
of size equal to the number of qubits in the circuit, which store the measurements. -
measure_active()
-
Adds a
barrier
followed by ameasure
operation to all active qubits in the circuit. A qubit is active if it has at least one other operation acting upon it. Creates aClassicalRegister
of size equal to the number of active qubits in the circuit, which store the measurements. -
remove_final_measurements()
-
Removes all final measurements and preceeding
barrier
from a circuit. A measurement is considered "final" if it is not followed by any other operation, excluding barriers and other measurements. After the measurements are removed, if all of the classical bits in theClassicalRegister
are idle (have no operations attached to them), then theClassicalRegister
is removed.
Examples:
# Using measure_all() circuit = QuantumCircuit(2) circuit.h(0) circuit.measure_all() circuit.draw() # A ClassicalRegister with prefix measure was created. # It has 2 clbits because there are 2 qubits to measure ┌───┐ ░ ┌─┐ q_0: |0>┤ H ├─░─┤M├─── └───┘ ░ └╥┘┌─┐ q_1: |0>──────░──╫─┤M├ ░ ║ └╥┘ measure_0: 0 ═════════╩══╬═ ║ measure_1: 0 ════════════╩═ # Using measure_active() circuit = QuantumCircuit(2) circuit.h(0) circuit.measure_active() circuit.draw() # This ClassicalRegister only has 1 clbit because only 1 qubit is active ┌───┐ ░ ┌─┐ q_0: |0>┤ H ├─░─┤M├ └───┘ ░ └╥┘ q_1: |0>──────░──╫─ ░ ║ measure_0: 0 ═════════╩═ # Using remove_final_measurements() # Assuming circuit_all and circuit_active are the circuits from the measure_all and # measure_active examples above respectively circuit_all.remove_final_measurements() circuit_all.draw() # The ClassicalRegister is removed because, after the measurements were removed, # all of its clbits were idle ┌───┐ q_0: |0>┤ H ├ └───┘ q_1: |0>───── circuit_active.remove_final_measurements() circuit_active.draw() # This will result in the same circuit ┌───┐ q_0: |0>┤ H ├ └───┘ q_1: |0>─────
-
-
Initial support for executing experiments on ion trap backends has been added.
-
An Rxx gate (rxx) and a global Mølmer–Sørensen gate (ms) have been added to the standard gate set.
-
A Cnot to Rxx/Rx/Ry decomposer
cnot_rxx_decompose
and a single qubit Euler angle decomposerOneQubitEulerDecomposer
have been added to thequantum_info.synthesis
module. -
A transpiler pass
MSBasisDecomposer
has been added to unroll circuits defined over U3 and Cnot gates into a circuit defined over Rxx,Ry and Rx. This pass will be included in preset pass managers for backends which include the 'rxx' gate in their supported basis gates. -
The backends in
qiskit.test.mock
now contain a snapshot of real device calibration data. This is accessible via theproperties()
method for each backend. This can be used to test any code that depends on backend properties, such as noise-adaptive transpiler passes or device noise models for simulation. This will create a faster testing and development cycle without the need to go to live backends. -
Allows the Result class to return partial results. If a valid result schema is loaded that contains some experiments which succeeded and some which failed, this allows accessing the data from experiments that succeeded, while raising an exception for experiments that failed and displaying the appropriate error message for the failed results.
-
An
ax
kwarg has been added to the following visualization functions:-
qiskit.visualization.plot_histogram
-
qiskit.visualization.plot_state_paulivec
-
qiskit.visualization.plot_state_qsphere
-
qiskit.visualization.circuit_drawer
(mpl
backend only) -
qiskit.QuantumCircuit.draw
(mpl
backend only)
This kwarg is used to pass in a
matplotlib.axes.Axes
object to the visualization functions. This enables integrating these visualization functions into a larger visualization workflow. Also, if an ax kwarg is specified then there is no return from the visualization functions. -
-
An
ax_real
andax_imag
kwarg has been added to the following visualization functions:-
qiskit.visualization.plot_state_hinton
-
qiskit.visualization.plot_state_city
These new kargs work the same as the newly added
ax
kwargs for other visualization functions. However because these plots use two axes (one for the real component, the other for the imaginary component). Having two kwargs also provides the flexibility to only generate a visualization for one of the components instead of always doing both. For example:from matplotlib import pyplot as plt from qiskit.visualization import plot_state_hinton ax = plt . gca () plot_state_hinton ( psi , ax_real = ax )
will only generate a plot of the real component.
-
-
A given pass manager now can be edited with the new method replace. This method allows to replace a particular stage in a pass manager, which can be handy when dealing with preset pass managers. For example, let's edit the layout selector of the pass manager used at optimization level 0:
from qiskit.transpiler.preset_passmanagers.level0 import level_0_pass_manager from qiskit.transpiler.transpile_config import TranspileConfig pass_manager = level_0_pass_manager ( TranspileConfig ( coupling_map = CouplingMap ([[ 0 , 1 ]]))) pass_manager . draw ()
[ 0 ] FlowLinear : SetLayout [ 1 ] Conditional : TrivialLayout [ 2 ] FlowLinear : FullAncillaAllocation , EnlargeWithAncilla , ApplyLayout [ 3 ] FlowLinear : Unroller
The layout selection is set in the stage [1]. Let's replace it with DenseLayout:
from qiskit.transpiler.passes import DenseLayout pass_manager . replace ( 1 , DenseLayout ( coupling_map ), condition = lambda property_set : not property_set [ 'layout' ]) pass_manager . draw ()
[ 0 ] FlowLinear : SetLayout [ 1 ] Conditional : DenseLayout [ 2 ] FlowLinear : FullAncillaAllocation , EnlargeWithAncilla , ApplyLayout [ 3 ] FlowLinear : Unroller
If you want to replace it without any condition, you can use set-item shortcut:
pass_manager [ 1 ] = DenseLayout ( coupling_map ) pass_manager . draw ()
[ 0 ] FlowLinear : SetLayout [ 1 ] FlowLinear : DenseLayout [ 2 ] FlowLinear : FullAncillaAllocation , EnlargeWithAncilla , ApplyLayout [ 3 ] FlowLinear : Unroller
-
Introduced a new pulse command
Delay
which may be inserted into a pulseSchedule
. This command accepts aduration
and may be added to anyChannel
. Other commands may not be scheduled on a channel during a delay.The delay can be added just like any other pulse command. For example:
from qiskit import pulse from qiskit.pulse.utils import pad dc0 = pulse . DriveChannel ( 0 ) delay = pulse . Delay ( 1 ) test_pulse = pulse . SamplePulse ([ 1.0 ]) sched = pulse . Schedule () sched += test_pulse ( dc0 ) . shift ( 1 ) # build padded schedule by hand ref_sched = delay ( dc0 ) | sched # pad schedule padded_sched = pad ( sched ) assert padded_sched == ref_sched
One may also pass additional channels to be padded and a time to pad until, for example:
from qiskit import pulse from qiskit.pulse.utils import pad dc0 = pulse . DriveChannel ( 0 ) dc1 = pulse . DriveChannel ( 1 ) delay = pulse . Delay ( 1 ) test_pulse = pulse . SamplePulse ([ 1.0 ]) sched = pulse . Schedule () sched += test_pulse ( dc0 ) . shift ( 1 ) # build padded schedule by hand ref_sched = delay ( dc0 ) | delay ( dc1 ) | sched # pad schedule across both channels until up until the first time step padded_sched = pad ( sched , channels = [ dc0 , dc1 ], until = 1 ) assert padded_sched == ref_sched
Upgrade Notes¶
-
Assignments and modifications to the
data
attribute ofqiskit.QuantumCircuit
objects are now validated following the same rules used throughout theQuantumCircuit
API. This was done to improve the performance of the circuits API since we can now assume thedata
attribute is in a known format. If you were manually modifying thedata
attribute of a circuit object before this may no longer work if your modifications resulted in a data structure other than the list of instructions with context in the format[(instruction, qargs, cargs)]
-
The transpiler default passmanager for optimization level 2 now uses the
DenseLayout
layout selection mechanism by default instead ofNoiseAdaptiveLayout
. TheDenselayout
pass has also been modified to be made noise-aware. -
The deprecated
DeviceSpecification
class has been removed. Instead you should use thePulseChannelSpec
. For example, you can run something like:device = pulse . PulseChannelSpec . from_backend ( backend ) device . drives [ 0 ] # for DeviceSpecification, this was device.q[0].drive device . memoryslots # this was device.mem
-
The deprecated module
qiskit.pulse.ops
has been removed. UseSchedule
andInstruction
methods directly. For example, rather than:ops . union ( schedule_0 , schedule_1 ) ops . union ( instruction , schedule ) # etc
Instead please use:
schedule_0 . union ( schedule_1 ) instruction . union ( schedule )
This same pattern applies to other
ops
functions:insert
,shift
,append
, andflatten
.
Deprecation Notes¶
-
Using the
control
property ofqiskit.circuit.Instruction
for classical control is now deprecated. In the future this property will be used for quantum control. Classically conditioned operations will instead be handled by thecondition
property ofqiskit.circuit.Instruction
. -
Support for setting
qiskit.circuit.Instruction
parameters with an object of typeqiskit.qasm.node.Node
has been deprecated.Node
objects that were previously used as parameters should be converted to a supported type prior to initializing a newInstruction
object or calling theInstruction.params
setter. Supported types areint
,float
,complex
,str
,qiskit.circuit.ParameterExpression
, ornumpy.ndarray
. -
In the qiskit 0.9.0 release the representation of bits (both qubits and classical bits) changed from tuples of the form
(register, index)
to be instances of the classesqiskit.circuit.Qubit
andqiskit.circuit.Clbit
. For backwards compatibility comparing the equality between a legacy tuple and the bit classes was supported as everything transitioned from tuples to being objects. This support is now deprecated and will be removed in the future. Everything should use the bit classes instead of tuples moving forward. -
When the
mpl
output is used for eitherqiskit.QuantumCircuit.draw()
orqiskit.visualization.circuit_drawer()
and thestyle
kwarg is used, passing in unsupported dictionary keys as part of thestyle`
dictionary is now deprecated. Where these unknown arguments were previously silently ignored, in the future, unsupported keys will raise an exception. -
The
line length
kwarg for theqiskit.QuantumCircuit.draw()
method and theqiskit.visualization.circuit_drawer()
function with the text output mode is deprecated. It has been replaced by thefold
kwarg which will behave identically for the text output mode (but also now supports the mpl output mode too).line_length
will be removed in a future release so calls should be updated to usefold
instead. -
The
fold
field in thestyle
dict kwarg for theqiskit.QuantumCircuit.draw()
method and theqiskit.visualization.circuit_drawer()
function has been deprecated. It has been replaced by thefold
kwarg on both functions. This kwarg behaves identically to the field in the style dict.
Bug Fixes¶
-
Instructions layering which underlies all types of circuit drawing has changed to address right/left justification. This sometimes results in output which is topologically equivalent to the rendering in prior versions but visually different than previously rendered. Fixes issue #2802
-
Add
memory_slots
toQobjExperimentHeader
of pulse Qobj. This fixes a bug in the data format ofmeas_level=2
results of pulse experiments. Measured quantum states are returned as a bit string with zero padding based on the number set formemory_slots
. -
Fixed the visualization of the rzz gate in the latex circuit drawer to match the cu1 gate to reflect the symmetry in the rzz gate. The fix is based on the cds command of the qcircuit latex package. Fixes issue #1957
Other Notes¶
-
matplotlib.figure.Figure
objects returned by visualization functions are no longer always closed by default. Instead the returned figure objects are only closed if the configured matplotlib backend is an inline jupyter backend(either set with%matplotlib inline
or%matplotlib notebook
). Output figure objects are still closed with these backends to avoid duplicate outputs in jupyter notebooks (which is why theFigure.close()
were originally added).
IBM Q Provider 0.3¶
No Change
Qiskit 0.12.0¶
Terra 0.9¶
Prelude¶
The 0.9 release includes many new features and many bug fixes. The biggest changes for this release are new debugging capabilities for PassManagers. This includes a function to visualize a PassManager, the ability to add a callback function to a PassManager, and logging of passes run in the PassManager. Additionally, this release standardizes the way that you can set an initial layout for your circuit. So now you can leverage initial_layout
the kwarg parameter on qiskit.compiler.transpile()
and qiskit.execute()
and the qubits in the circuit will get laid out on the desire qubits on the device. Visualization of circuits will now also show this clearly when visualizing a circuit that has been transpiled with a layout.
New Features¶
-
A
DAGCircuit
object (i.e. the graph representation of a QuantumCircuit where operation dependencies are explicit) can now be visualized with the.draw()
method. This is in line with Qiskit's philosophy of easy visualization. Other objects which support a.draw()
method areQuantumCircuit
,PassManager
, andSchedule
. -
Added a new visualization function
qiskit.visualization.plot_error_map()
to plot the error map for a given backend. It takes in a backend object from the qiskit-ibmq-provider and will plot the current error map for that device. -
Both
qiskit.QuantumCircuit.draw()
andqiskit.visualization.circuit_drawer()
now support annotating the qubits in the visualization with layout information. If theQuantumCircuit
object being drawn includes layout metadata (which is normally only set on the circuit output fromtranspile()
calls) then by default that layout will be shown on the diagram. This is done for all circuit drawer backends. For example:from qiskit import ClassicalRegister , QuantumCircuit , QuantumRegister from qiskit.compiler import transpile qr = QuantumRegister ( 2 , 'userqr' ) cr = ClassicalRegister ( 2 , 'c0' ) qc = QuantumCircuit ( qr , cr ) qc . h ( qr [ 0 ]) qc . cx ( qr [ 0 ], qr [ 1 ]) qc . y ( qr [ 0 ]) qc . x ( qr [ 1 ]) qc . measure ( qr , cr ) # Melbourne coupling map coupling_map = [[ 1 , 0 ], [ 1 , 2 ], [ 2 , 3 ], [ 4 , 3 ], [ 4 , 10 ], [ 5 , 4 ], [ 5 , 6 ], [ 5 , 9 ], [ 6 , 8 ], [ 7 , 8 ], [ 9 , 8 ], [ 9 , 10 ], [ 11 , 3 ], [ 11 , 10 ], [ 11 , 12 ], [ 12 , 2 ], [ 13 , 1 ], [ 13 , 12 ]] qc_result = transpile ( qc , basis_gates = [ 'u1' , 'u2' , 'u3' , 'cx' , 'id' ], coupling_map = coupling_map , optimization_level = 0 ) qc . draw ( output = 'text' )
will yield a diagram like:
┌──────────┐┌──────────┐┌───┐┌──────────┐┌──────────────────┐┌─┐ (userqr0) q0|0>┤ U2(0,pi) ├┤ U2(0,pi) ├┤ X ├┤ U2(0,pi) ├┤ U3(pi,pi/2,pi/2) ├┤M├─── ├──────────┤└──────────┘└─┬─┘├──────────┤└─┬─────────────┬──┘└╥┘┌─┐ (userqr1) q1|0>┤ U2(0,pi) ├──────────────■──┤ U2(0,pi) ├──┤ U3(pi,0,pi) ├────╫─┤M├ └──────────┘ └──────────┘ └─────────────┘ ║ └╥┘ (ancilla0) q2|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla1) q3|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla2) q4|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla3) q5|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla4) q6|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla5) q7|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla6) q8|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla7) q9|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla8) q10|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla9) q11|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla10) q12|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ (ancilla11) q13|0>──────────────────────────────────────────────────────────────╫──╫─ ║ ║ c0_0: 0 ══════════════════════════════════════════════════════════════╩══╬═ ║ c0_1: 0 ═════════════════════════════════════════════════════════════════╩═
If you do not want the layout to be shown on transpiled circuits (or any other circuits with a layout set) there is a new boolean kwarg for both functions,
with_layout
(which defaultsTrue
), which when setFalse
will disable the layout annotation in the output circuits. -
A new analysis pass
CountOpsLongest
was added to retrieve the number of operations on the longest path of the DAGCircuit. When used it will add acount_ops_longest_path
key to the property set dictionary. You can add it to your a passmanager with something like:from qiskit.transpiler.passes import CountOpsLongestPath from qiskit.transpiler.passes import CxCancellation from qiskit.transpiler import PassManager pm = PassManager () pm . append ( CountOpsLongestPath ())
and then access the longest path via the property set value with something like:
pm . append ( CxCancellation (), condition = lambda property_set : property_set [ 'count_ops_longest_path' ] < 5 )
which will set a condition on that pass based on the longest path.
-
Two new functions,
sech()
andsech_deriv()
were added to the pulse library moduleqiskit.pulse.pulse_lib
for creating an unnormalized hyperbolic secantSamplePulse
object and an unnormalized hyperbolic secant derviativeSamplePulse
object respectively. -
A new kwarg option
vertical_compression
was added to theQuantumCircuit.draw()
method and theqiskit.visualization.circuit_drawer()
function. This option only works with thetext
backend. This option can be set to eitherhigh
,medium
(the default), orlow
to adjust how much vertical space is used by the output visualization. -
A new kwarg boolean option
idle_wires
was added to theQuantumCircuit.draw()
method and theqiskit.visualization.circuit_drawer()
function. It works for all drawer backends. Whenidle_wires
is set False in a drawer call the drawer will not draw any bits that do not have any circuit elements in the output quantum circuit visualization. -
A new PassManager visualizer function
qiskit.visualization.pass_mamanger_drawer()
was added. This function takes in a PassManager object and will generate a flow control diagram of all the passes run in the PassManager. -
When creating a PassManager you can now specify a callback function that if specified will be run after each pass is executed. This function gets passed a set of kwargs on each call with the state of the pass manager after each pass execution. Currently these kwargs are:
-
pass_
(Pass
): the pass being run -
dag
(DAGCircuit
): the dag output of the pass -
time
(float
): the time to execute the pass -
property_set
(PropertySet
): the property set -
count
(int
): the index for the pass execution
However, it's worth noting that while these arguments are set for the 0.9 release they expose the internals of the pass manager and are subject to change in future release.
For example you can use this to create a callback function that will visualize the circuit output after each pass is executed:
from qiskit.transpiler import PassManager def my_callback ( ** kwargs ): print ( kwargs [ 'dag' ]) pm = PassManager ( callback = my_callback )
Additionally you can specify the callback function when using
qiskit.compiler.transpile()
:from qiskit.compiler import transpile def my_callback ( ** kwargs ): print ( kwargs [ 'pass' ]) transpile ( circ , callback = my_callback )
-
-
A new method
filter()
was added to theqiskit.pulse.Schedule
class. This enables filtering the instructions in a schedule. For example, filtering by instruction type:from qiskit.pulse import Schedule from qiskit.pulse.commands import Acquire from qiskit.pulse.commands import AcquireInstruction from qiskit.pulse.commands import FrameChange sched = Schedule ( name = 'MyExperiment' ) sched . insert ( 0 , FrameChange ( phase =- 1.57 )( device )) sched . insert ( 60 , Acquire ( 5 )) acquire_sched = sched . filter ( instruction_types = [ AcquireInstruction ])
-
Additional decomposition methods for several types of gates. These methods will use different decomposition techniques to break down a gate into a sequence of CNOTs and single qubit gates. The following methods are added:
Method
Description
QuantumCircuit.iso()
Add an arbitrary isometry from m to n qubits to a circuit. This allows for attaching arbitrary unitaries on n qubits (m=n) or to prepare any state of n qubits (m=0)
QuantumCircuit.diag_gate()
Add a diagonal gate to the circuit
QuantumCircuit.squ()
Decompose an arbitrary 2x2 unitary into three rotation gates and add to a circuit
QuantumCircuit.ucg()
Attach an uniformly controlled gate (also called a multiplexed gate) to a circuit
QuantumCircuit.ucx()
Attach a uniformly controlled (also called multiplexed) Rx rotation gate to a circuit
QuantumCircuit.ucy()
Attach a uniformly controlled (also called multiplexed) Ry rotation gate to a circuit
QuantumCircuit.ucz()
Attach a uniformly controlled (also called multiplexed) Rz rotation gate to a circuit
-
Addition of Gray-Synth and Patel–Markov–Hayes algorithms for synthesis of CNOT-Phase and CNOT-only linear circuits. These functions allow the synthesis of circuits that consist of only CNOT gates given a linear function or a circuit that consists of only CNOT and phase gates given a matrix description.
-
A new function
random_circuit
was added to theqiskit.circuit.random
module. This function will generate a random circuit of a specified size by randomly selecting different gates and adding them to the circuit. For example, you can use this to generate a 5-qubit circuit with a depth of 10 using:from qiskit.circuit.random import random_circuit circ = random_circuit ( 5 , 10 )
-
A new kwarg
output_names
was added to theqiskit.compiler.transpile()
function. This kwarg takes in a string or a list of strings and uses those as the value of the circuit name for the output circuits that get returned by thetranspile()
call. For example:from qiskit.compiler import transpile my_circs = [ circ_a , circ_b ] tcirc_a , tcirc_b = transpile ( my_circs , output_names = [ 'Circuit A' , 'Circuit B' ])
the
name
attribute on tcirc_a and tcirc_b will be'Circuit A'
and'Circuit B'
respectively. -
A new method
equiv()
was added to theqiskit.quantum_info.Operator
andqiskit.quantum_info.Statevector
classes. These methods are used to check whether a secondOperator
object orStatevector
is equivalent up to global phase. -
The user config file has several new options:
-
The
circuit_drawer
field now accepts an auto value. When set as the value for thecircuit_drawer
field the default drawer backend will be mpl if it is available, otherwise the text backend will be used. -
A new field
circuit_mpl_style
can be used to set the default style used by the matplotlib circuit drawer. Valid values for this field arebw
anddefault
to set the default to a black and white or the default color style respectively. -
A new field
transpile_optimization_level
can be used to set the default transpiler optimization level to use for calls toqiskit.compiler.transpile()
. The value can be set to either 0, 1, 2, or 3.
-
-
Introduced a new pulse command
Delay
which may be inserted into a pulseSchedule
. This command accepts aduration
and may be added to anyChannel
. Other commands may not be scheduled on a channel during a delay.The delay can be added just like any other pulse command. For example:
from qiskit import pulse drive_channel = pulse . DriveChannel ( 0 ) delay = pulse . Delay ( 20 ) sched = pulse . Schedule () sched += delay ( drive_channel )
Upgrade Notes¶
-
The previously deprecated
qiskit._util
module has been removed.qiskit.util
should be used instead. -
The
QuantumCircuit.count_ops()
method now returns anOrderedDict
object instead of adict
. This should be compatible for most use cases sinceOrderedDict
is adict
subclass. However type checks and other class checks might need to be updated. -
The
DAGCircuit.width()
method now returns the total number quantum bits and classical bits. Before it would only return the number of quantum bits. If you require just the number of quantum bits you can useDAGCircuit.num_qubits()
instead. -
The function
DAGCircuit.num_cbits()
has been removed. Instead you can useDAGCircuit.num_clbits()
. -
Individual quantum bits and classical bits are no longer represented as
(register, index)
tuples. They are now instances of Qubit and Clbit classes. If you're dealing with individual bits make sure that you update any usage or type checks to look for these new classes instead of tuples. -
The preset passmanager classes
qiskit.transpiler.preset_passmanagers.default_pass_manager
andqiskit.transpiler.preset_passmanagers.default_pass_manager_simulator
(which were the previous default pass managers forqiskit.compiler.transpile()
calls) have been removed. If you were manually using this pass managers switch to the new default,qiskit.transpile.preset_passmanagers.level1_pass_manager
. -
The
LegacySwap
pass has been removed. If you were using it in a custom pass manager, it's usage can be replaced by theStochasticSwap
pass, which is a faster more stable version. All the preset passmanagers have been updated to useStochasticSwap
pass instead of theLegacySwap
. -
The following deprecated
qiskit.dagcircuit.DAGCircuit
methods have been removed:-
DAGCircuit.get_qubits()
- UseDAGCircuit.qubits()
instead -
DAGCircuit.get_bits()
- UseDAGCircuit.clbits()
instead -
DAGCircuit.qasm()
- Use a combination ofqiskit.converters.dag_to_circuit()
andQuantumCircuit.qasm()
. For example:from qiskit.dagcircuit import DAGCircuit from qiskit.converters import dag_to_circuit my_dag = DAGCircuit () qasm = dag_to_circuit ( my_dag ) . qasm ()
-
DAGCircuit.get_op_nodes()
- UseDAGCircuit.op_nodes()
instead. Note that the return type is a list ofDAGNode
objects forop_nodes()
instead of the list of tuples previously returned byget_op_nodes()
. -
DAGCircuit.get_gate_nodes()
- UseDAGCircuit.gate_nodes()
instead. Note that the return type is a list ofDAGNode
objects forgate_nodes()
instead of the list of tuples previously returned byget_gate_nodes()
. -
DAGCircuit.get_named_nodes()
- UseDAGCircuit.named_nodes()
instead. Note that the return type is a list ofDAGNode
objects fornamed_nodes()
instead of the list of node_ids previously returned byget_named_nodes()
. -
DAGCircuit.get_2q_nodes()
- UseDAGCircuit.twoQ_gates()
instead. Note that the return type is a list ofDAGNode
objects fortwoQ_gates()
instead of the list of data_dicts previously returned byget_2q_nodes()
. -
DAGCircuit.get_3q_or_more_nodes()
- UseDAGCircuit.threeQ_or_more_gates()
instead. Note that the return type is a list ofDAGNode
objects forthreeQ_or_more_gates()
instead of the list of tuples previously returned byget_3q_or_more_nodes()
.
-
-
The following
qiskit.dagcircuit.DAGCircuit
methods had deprecated support for accepting anode_id
as a parameter. This has been removed and now onlyDAGNode
objects are accepted as input:-
successors()
-
predecessors()
-
ancestors()
-
descendants()
-
bfs_successors()
-
quantum_successors()
-
remove_op_node()
-
remove_ancestors_of()
-
remove_descendants_of()
-
remove_nonancestors_of()
-
remove_nondescendants_of()
-
substitute_node_with_dag()
-
-
The
qiskit.dagcircuit.DAGCircuit
methodrename_register()
has been removed. This was unused by all the qiskit code. If you were relying on it externally you'll have to re-implement is an external function. -
The
qiskit.dagcircuit.DAGCircuit
propertymulti_graph
has been removed. Direct access to the underlyingnetworkx
multi_graph
object isn't supported anymore. The API provided by theDAGCircuit
class should be used instead. -
The deprecated exception class
qiskit.qiskiterror.QiskitError
has been removed. Instead you should useqiskit.exceptions.QiskitError
. -
The boolean kwargs,
ignore_requires
andignore_preserves
from theqiskit.transpiler.PassManager
constructor have been removed. These are no longer valid options. -
The module
qiskit.tools.logging
has been removed. This module was not used by anything and added nothing over the interfaces that Python's standard librarylogging
module provides. If you want to set a custom formatter for logging use the standard librarylogging
module instead. -
The
CompositeGate
class has been removed. Instead you should directly create a instruction object from a circuit and append that to your circuit. For example, you can run something like:custom_gate_circ = qiskit . QuantumCircuit ( 2 ) custom_gate_circ . x ( 1 ) custom_gate_circ . h ( 0 ) custom_gate_circ . cx ( 0 , 1 ) custom_gate = custom_gate_circ . to_instruction ()
-
The previously deprecated kwargs,
seed
andconfig
forqiskit.compiler.assemble()
have been removed useseed_simulator
andrun_config
respectively instead. -
The previously deprecated converters
qiskit.converters.qobj_to_circuits()
andqiskit.converters.circuits_to_qobj()
have been removed. Useqiskit.assembler.disassemble()
andqiskit.compiler.assemble()
respectively instead. -
The previously deprecated kwarg
seed_mapper
forqiskit.compiler.transpile()
has been removed. Instead you should useseed_transpiler
-
The previously deprecated kwargs
seed
,seed_mapper
,config
, andcircuits
for theqiskit.execute()
function have been removed. Useseed_simulator
,seed_transpiler
,run_config
, andexperiments
arguments respectively instead. -
The previously deprecated
qiskit.tools.qcvv
module has been removed use qiskit-ignis instead. -
The previously deprecated functions
qiskit.transpiler.transpile()
andqiskit.transpiler.transpile_dag()
have been removed. Instead you should useqiskit.compiler.transpile
. If you were usingtranspile_dag()
this can be replaced by running:circ = qiskit . converters . dag_to_circuit ( dag ) out_circ = qiskit . compiler . transpile ( circ ) qiskit . converters . circuit_to_dag ( out_circ )
-
The previously deprecated function
qiskit.compile()
has been removed instead you should useqiskit.compiler.transpile()
andqiskit.compiler.assemble()
. -
The jupyter cell magic
%%qiskit_progress_bar
fromqiskit.tools.jupyter
has been changed to a line magic. This was done to better reflect how the magic is used and how it works. If you were using the%%qiskit_progress_bar
cell magic in an existing notebook, you will have to update this to be a line magic by changing it to be%qiskit_progress_bar
instead. Everything else should behave identically. -
The deprecated function
qiskit.tools.qi.qi.random_unitary_matrix()
has been removed. You should use theqiskit.quantum_info.random.random_unitary()
function instead. -
The deprecated function
qiskit.tools.qi.qi.random_density_matrix()
has been removed. You should use theqiskit.quantum_info.random.random_density_matrix()
function instead. -
The deprecated function
qiskit.tools.qi.qi.purity()
has been removed. You should theqiskit.quantum_info.purity()
function instead. -
The deprecated
QuantumCircuit._attach()
method has been removed. You should useQuantumCircuit.append()
instead. -
The
qiskit.qasm.Qasm
methodget_filename()
has been removed. You can use thereturn_filename()
method instead. -
The deprecated
qiskit.mapper
module has been removed. The list of functions and classes with their alternatives are:-
qiskit.mapper.CouplingMap
:qiskit.transpiler.CouplingMap
should be used instead. -
qiskit.mapper.Layout
:qiskit.transpiler.Layout
should be used instead -
qiskit.mapper.compiling.euler_angles_1q()
:qiskit.quantum_info.synthesis.euler_angles_1q()
should be used instead -
qiskit.mapper.compiling.two_qubit_kak()
:qiskit.quantum_info.synthesis.two_qubit_cnot_decompose()
should be used instead.
The deprecated exception classes
qiskit.mapper.exceptions.CouplingError
andqiskit.mapper.exceptions.LayoutError
don't have an alternative since they serve no purpose without aqiskit.mapper
module. -
-
The
qiskit.pulse.samplers
module has been moved toqiskit.pulse.pulse_lib.samplers
. You will need to update imports ofqiskit.pulse.samplers
toqiskit.pulse.pulse_lib.samplers
. -
seaborn is now a dependency for the function
qiskit.visualization.plot_state_qsphere()
. It is needed to generate proper angular color maps for the visualization. Theqiskit-terra[visualization]
extras install target has been updated to installseaborn>=0.9.0
If you are using visualizations and specifically theplot_state_qsphere()
function you can use that to installseaborn
or just manually runpip install seaborn>=0.9.0
-
The previously deprecated functions
qiksit.visualization.plot_state
andqiskit.visualization.iplot_state
have been removed. Instead you should use the specific function for each plot type. You can refer to the following tables to map the deprecated functions to their equivalent new ones:Qiskit Terra 0.6
Qiskit Terra 0.7+
plot_state(rho)
plot_state_city(rho)
plot_state(rho, method='city')
plot_state_city(rho)
plot_state(rho, method='paulivec')
plot_state_paulivec(rho)
plot_state(rho, method='qsphere')
plot_state_qsphere(rho)
plot_state(rho, method='bloch')
plot_bloch_multivector(rho)
plot_state(rho, method='hinton')
plot_state_hinton(rho)
-
The
pylatexenc
andpillow
dependencies for thelatex
andlatex_source
circuit drawer backends are no longer listed as requirements. If you are going to use the latex circuit drawers ensure you have both packages installed or use the setuptools extras to install it along with qiskit-terra:pip install qiskit - terra [ visualization ]
-
The root of the
qiskit
namespace will now emit a warning on import if eitherqiskit.IBMQ
orqiskit.Aer
could not be setup. This will occur whenever anything in theqiskit
namespace is imported. These warnings were added to make it clear for users up front if they're running qiskit and the qiskit-aer and qiskit-ibmq-provider packages could not be found. It's not always clear if the packages are missing or python packaging/pip installed an element incorrectly until you go to use them and get an emptyImportError
. These warnings should make it clear up front if there these commonly used aliases are missing.However, for users that choose not to use either qiskit-aer or qiskit-ibmq-provider this might cause additional noise. For these users these warnings are easily suppressable using Python's standard library
warnings
. Users can suppress the warnings by putting these two lines before any imports from qiskit:import warnings warnings . filterwarnings ( 'ignore' , category = RuntimeWarning , module = 'qiskit' )
This will suppress the warnings emitted by not having qiskit-aer or qiskit-ibmq-provider installed, but still preserve any other warnings emitted by qiskit or any other package.
Deprecation Notes¶
-
The
U
andCX
gates have been deprecated. If you're using these gates in your code you should update them to useu3
andcx
instead. For example, if you're using the circuit gate functionscircuit.u_base()
andcircuit.cx_base()
you should update these to becircuit.u3()
andcircuit.cx()
respectively. -
The
u0
gate has been deprecated in favor of using multipleiden
gates and it will be removed in the future. If you're using theu0
gate in your circuit you should update your calls to useiden
. For example, f you were usingcircuit.u0(2)
in your circuit before that should be updated to be:circuit . iden () circuit . iden ()
instead.
-
The
qiskit.pulse.DeviceSpecification
class is deprecated now. Instead you should useqiskit.pulse.PulseChannelSpec
. -
Accessing a
qiskit.circuit.Qubit
,qiskit.circuit.Clbit
, orqiskit.circuit.Bit
class by index is deprecated (for compatibility with the(register, index)
tuples that these classes replaced). Instead you should use theregister
andindex
attributes. -
Passing in a bit to the
qiskit.QuantumCircuit
methodappend
as a tuple(register, index)
is deprecated. Instead bit objects should be used directly. -
Accessing the elements of a
qiskit.transpiler.Layout
object with a tuple(register, index)
is deprecated. Instead a bit object should be used directly. -
The
qiskit.transpiler.Layout
constructor methodqiskit.transpiler.Layout.from_tuplelist()
is deprecated. Instead the constructorqiskit.transpiler.Layout.from_qubit_list()
should be used. -
The module
qiskit.pulse.ops
has been deprecated. All the functions it provided:-
union
-
flatten
-
shift
-
insert
-
append
have equivalent methods available directly on the
qiskit.pulse.Schedule
andqiskit.pulse.Instruction
classes. Those methods should be used instead. -
-
The
qiskit.qasm.Qasm
methodget_tokens()
is deprecated. Instead you should use thegenerate_tokens()
method. -
The
qiskit.qasm.qasmparser.QasmParser
methodget_tokens()
is deprecated. Instead you should use theread_tokens()
method. -
The
as_dict()
method for the Qobj class has been deprecated and will be removed in the future. You should replace calls to it withto_dict()
instead.
Bug Fixes¶
-
The definition of the
CU3Gate
has been changed to be equivalent to the canonical definition of a controlledU3Gate
. -
The handling of layout in the pass manager has been standardized. This fixes several reported issues with handling layout. The
initial_layout
kwarg parameter onqiskit.compiler.transpile()
andqiskit.execute()
will now lay out your qubits from the circuit onto the desired qubits on the device when transpiling circuits. -
Support for n-qubit unitaries was added to the BasicAer simulator and
unitary
(arbitrary unitary gates) was added to the set of basis gates for the simulators -
The
qiskit.visualization.plost_state_qsphere()
has been updated to fix several issues with it. Now output Q Sphere visualization will be correctly generated and the following aspects have been updated:-
All complementary basis states are antipodal
-
Phase is indicated by color of line and marker on sphere's surface
-
- Probability is indicated by translucency of line and volume of marker on
-
sphere's surface
-
Other Notes¶
-
The default PassManager for
qiskit.compiler.transpile()
andqiskit.execute()
has been changed to optimization level 1 pass manager defined atqiskit.transpile.preset_passmanagers.level1_pass_manager
. -
All the circuit drawer backends now will express gate parameters in a circuit as common fractions of pi in the output visualization. If the value of a parameter can be expressed as a fraction of pi that will be used instead of the numeric equivalent.
-
When using
qiskit.assembler.assemble_schedules()
if you do not provide the number of memory_slots to use the number will be inferred based on the number of acquisitions in the input schedules. -
The deprecation warning on the
qiskit.dagcircuit.DAGCircuit
propertynode_counter
has been removed. The behavior change being warned about was put into effect when the warning was added, so warning that it had changed served no purpose. -
Calls to
PassManager.run()
now will emit python logging messages at the INFO level for each pass execution. These messages will include the Pass name and the total execution time of the pass. Python's standard logging was used because it allows Qiskit-Terra's logging to integrate in a standard way with other applications and libraries. All logging for the transpiler occurs under theqiskit.transpiler
namespace, as used bylogging.getLogger('qiskit.transpiler
). For example, to turn on DEBUG level logging for the transpiler you can run:import logging logging . basicConfig () logging . getLogger ( 'qiskit.transpiler' ) . setLevel ( logging . DEBUG )
which will set the log level for the transpiler to DEBUG and configure those messages to be printed to stderr.
Aer 0.3¶
-
There's a new high-performance Density Matrix Simulator that can be used in conjunction with our noise models, to better simulate real world scenarios.
-
We have added a Matrix Product State (MPS) simulator. MPS allows for efficient simulation of several classes of quantum circuits, even under presence of strong correlations and highly entangled states. For cases amenable to MPS, circuits with several hundred qubits and more can be exactly simulated, e.g., for the purpose of obtaining expectation values of observables.
-
Snapshots can be performed in all of our simulators.
-
Now we can measure sampling circuits with read-out errors too, not only ideal circuits.
-
We have increased some circuit optimizations with noise presence.
-
A better 2-qubit error approximations have been included.
-
Included some tools for making certain noisy simulations easier to craft and faster to simulate.
-
Increased performance with simulations that require less floating point numerical precision.
Ignis 0.2¶
Bug Fixes¶
-
Fixed a bug in RB fit error
-
Fixed a bug in the characterization fitter when selecting a qubit index to fit
Other Notes¶
-
Measurement mitigation now operates in parallel when applied to multiple results
-
Guess values for RB fitters are improved
Aqua 0.6¶
Added¶
-
Relative-Phase Toffoli gates
rccx
(with 2 controls) andrcccx
(with 3 controls). -
Variational form
RYCRX
-
A new
'basic-no-ancilla'
mode tomct
. -
Multi-controlled rotation gates
mcrx
,mcry
, andmcrz
as a generalu3
gate is not supported by graycode implementation -
Chemistry: ROHF open-shell support
-
Supported for all drivers: Gaussian16, PyQuante, PySCF and PSI4
-
HartreeFock initial state, UCCSD variational form and two qubit reduction for parity mapping now support different alpha and beta particle numbers for open shell support
-
-
Chemistry: UHF open-shell support
-
Supported for all drivers: Gaussian16, PyQuante, PySCF and PSI4
-
QMolecule extended to include integrals, coefficients etc for separate beta
-
-
Chemistry: QMolecule extended with integrals in atomic orbital basis to facilitate common access to these for experimentation
-
Supported for all drivers: Gaussian16, PyQuante, PySCF and PSI4
-
-
Chemistry: Additional PyQuante and PySCF driver configuration
-
Convergence tolerance and max convergence iteration controls.
-
For PySCF initial guess choice
-
-
Chemistry: Processing output added to debug log from PyQuante and PySCF computations (Gaussian16 and PSI4 outputs were already added to debug log)
-
Chemistry: Merged qiskit-chemistry into qiskit-aqua
-
Add
MatrixOperator
,WeightedPauliOperator
andTPBGroupedPauliOperator
class. -
Add
evolution_instruction
function to get registerless instruction of time evolution. -
Add
op_converter
module to unify the place in charge of converting different types of operators. -
Add
Z2Symmetries
class to encapsulate the Z2 symmetries info and has helper methods for tapering an Operator. -
Amplitude Estimation: added maximum likelihood postprocessing and confidence interval computation.
-
Maximum Likelihood Amplitude Estimation (MLAE): Implemented new algorithm for amplitude estimation based on maximum likelihood estimation, which reduces number of required qubits and circuit depth.
-
Added (piecewise) linearly and polynomially controlled Pauli-rotation circuits.
-
Add
q_equation_of_motion
to study excited state of a molecule, and add two algorithms to prepare the reference state.
Changed¶
-
Improve
mct
's'basic'
mode by using relative-phase Toffoli gates to build intermediate results. -
Adapt to Qiskit Terra's newly introduced
Qubit
class. -
Prevent
QPE/IQPE
from modifying inputOperator
objects. -
The PyEDA dependency was removed; corresponding oracles' underlying logic operations are now handled by SymPy.
-
Refactor the
Operator
class, each representation has its own classMatrixOperator
,WeightedPauliOperator
andTPBGroupedPauliOperator
. -
The
power
inevolution_instruction
was applied on the theta on the CRZ gate directly, the new version repeats the circuits to implement power. -
CircuitCache is OFF by default, and it can be set via environment variable now
QISKIT_AQUA_CIRCUIT_CACHE
.
Bug Fixes¶
-
A bug where
TruthTableOracle
would build incorrect circuits for truth tables with only a single1
value. -
A bug caused by
PyEDA
's indeterminism. -
A bug with
QPE/IQPE
's translation and stretch computation. -
Chemistry: Bravyi-Kitaev mapping fixed when num qubits was not a power of 2
-
Setup
initial_layout
inQuantumInstance
via a list.
Removed¶
-
General multi-controlled rotation gate
mcu3
is removed and replaced by multi-controlled rotation gatesmcrx
,mcry
, andmcrz
Deprecated¶
-
The
Operator
class is deprecated, in favor of usingMatrixOperator
,WeightedPauliOperator
andTPBGroupedPauliOperator
.
IBM Q Provider 0.3¶
No change
Qiskit 0.11.1¶
We have bumped up Qiskit micro version to 0.11.1 because IBM Q Provider has bumped its micro version as well.
Aqua 0.5¶
qiskit-aqua
has been updated to 0.5.3
to fix code related to changes in how gates inverses are done.
IBM Q Provider 0.3¶
The IBMQProvider
has been updated to version 0.3.1
to fix backward compatibility issues and work with the default 10 job limit in single calls to the IBM Q API v2.
Qiskit 0.11¶
We have bumped up Qiskit minor version to 0.11 because IBM Q Provider has bumped up its minor version too. On Aer, we have jumped from 0.2.1 to 0.2.3 because there was an issue detected right after releasing 0.2.2 and before Qiskit 0.11 went online.
Aer 0.2¶
New features¶
-
Added support for multi-controlled phase gates
-
Added optimized anti-diagonal single-qubit gates
Improvements¶
-
Introduced a technique called Fusion that increments performance of circuit execution Tuned threading strategy to gain performance in most common scenarios.
-
Some of the already implemented error models have been polished.
IBM Q Provider 0.3¶
The IBMQProvider
has been updated in order to default to use the new IBM Q Experience v2. Accessing the legacy IBM Q Experience v1 and QConsole will still be supported during the 0.3.x line until its final deprecation one month from the release. It is encouraged to update to the new IBM Q Experience to take advantage of the new functionality and features.
Updating to the new IBM Q Experience v2¶
If you have credentials for the legacy IBM Q Experience stored on disk, you can make use of the interactive helper:
from qiskit import IBMQ IBMQ . update_account ()
For more complex cases or fine tuning your configuration, the following methods are available:
-
the
IBMQ.delete_accounts()
can be used for resetting your configuration file. -
the
IBMQ.save_account('MY_TOKEN')
method can be used for saving your credentials, following the instructions in the IBM Q Experience v2 account page.
Updating your programs¶
When using the new IBM Q Experience v2 through the provider, access to backends is done via individual provider
instances (as opposed to accessing them directly through the qiskit.IBMQ
object as in previous versions), which allows for more granular control over the project you are using.
You can get a reference to the providers
that you have access to using the IBMQ.providers()
and IBMQ.get_provider()
methods:
from qiskit import IBMQ provider = IBMQ . load_account () my_providers = IBMQ . providers () provider_2 = IBMQ . get_provider ( hub = 'A' , group = 'B' , project = 'C' )
For convenience, IBMQ.load_account()
and IBMQ.enable_account()
will return a provider for the open access project, which is the default in the new IBM Q Experience v2.
For example, the following program in previous versions:
from qiskit import IBMQ IBMQ . load_accounts () backend = IBMQ . get_backend ( 'ibmqx4' ) backend_2 = IBMQ . get_backend ( 'ibmq_qasm_simulator' , hub = 'HUB2' )
Would be equivalent to the following program in the current version:
from qiskit import IBMQ provider = IBMQ . load_account () backend = provider . get_backend ( 'ibmqx4' ) provider_2 = IBMQ . get_provider ( hub = 'HUB2' ) backend_2 = provider_2 . get_backend ( 'ibmq_qasm_simulator' )
You can find more information and details in the IBM Q Provider documentation.
Qiskit 0.10¶
IBM Q Provider 0.2¶
New Features¶
-
The
IBMQProvider
supports connecting to the new version of the IBM Q API. Please note support for this version is still experimental #78. -
Added support for Circuits through the new API #79.
Bug Fixes¶
-
Fixed incorrect parsing of some API hub URLs #77.
-
Fixed noise model handling for remote simulators #84.
Qiskit 0.9¶
Terra 0.8¶
Highlights¶
-
Introduction of the Pulse module under
qiskit.pulse
, which includes tools for building pulse commands, scheduling them on pulse channels, visualization, and running them on IBM Q devices. -
Improved QuantumCircuit and Instruction classes, allowing for the composition of arbitrary sub-circuits into larger circuits, and also for creating parameterized circuits.
-
A powerful Quantum Info module under
qiskit.quantum_info
, providing tools to work with operators and channels and to use them inside circuits. -
New transpiler optimization passes and access to predefined transpiling routines.
New Features¶
-
The core
StochasticSwap
routine is implemented in Cython. -
Added
QuantumChannel
classes for manipulating quantum channels and CPTP maps. -
Support for parameterized circuits.
-
The
PassManager
interface has been improved and new functions added for easier interaction and usage with custom pass managers. -
Preset
PassManager
s are now included which offer a predetermined pipeline of transpiler passes. -
User configuration files to let local environments override default values for some functions.
-
New transpiler passes:
EnlargeWithAncilla
,Unroll2Q
,NoiseAdaptiveLayout
,OptimizeSwapBeforeMeasure
,RemoveDiagonalGatesBeforeMeasure
,CommutativeCancellation
,Collect2qBlocks
, andConsolidateBlocks
.
Compatibility Considerations¶
As part of the 0.8 release the following things have been deprecated and will either be removed or changed in a backwards incompatible manner in a future release. While not strictly necessary these are things to adjust for before the 0.9 (unless otherwise noted) release to avoid a breaking change in the future.
-
The methods prefixed by
_get
in theDAGCircuit
object are being renamed without that prefix. -
Changed elements in
couplinglist
ofCouplingMap
from tuples to lists. -
Unroller bases must now be explicit, and violation raises an informative
QiskitError
. -
The
qiskit.tools.qcvv
package is deprecated and will be removed in the in the future. You should migrate to using the Qiskit Ignis which replaces this module. -
The
qiskit.compile()
function is now deprecated in favor of explicitly using theqiskit.compiler.transpile()
function to transform a circuit, followed byqiskit.compiler.assemble()
to make a Qobj out of it. Instead ofcompile(...)
, useassemble(transpile(...), ...)
. -
qiskit.converters.qobj_to_circuits()
has been deprecated and will be removed in a future release. Insteadqiskit.assembler.disassemble()
should be used to extractQuantumCircuit
objects from a compiled Qobj. -
The
qiskit.mapper
namespace has been deprecated. TheLayout
andCouplingMap
classes can be accessed viaqiskit.transpiler
. -
A few functions in
qiskit.tools.qi.qi
have been deprecated and moved toqiskit.quantum_info
.
Please note that some backwards incompatible changes have been made during this release. The following notes contain information on how to adapt to these changes.
IBM Q Provider¶
The IBM Q provider was previously included in Terra, but it has been split out into a separate package qiskit-ibmq-provider
. This will need to be installed, either via pypi with pip install qiskit-ibmq-provider
or from source in order to access qiskit.IBMQ
or qiskit.providers.ibmq
. If you install qiskit with pip install qiskit
, that will automatically install all subpackages of the Qiskit project.
Cython Components¶
Starting in the 0.8 release the core stochastic swap routine is now implemented in Cython. This was done to significantly improve the performance of the swapper, however if you build Terra from source or run on a non-x86 or other platform without prebuilt wheels and install from source distribution you'll need to make sure that you have Cython installed prior to installing/building Qiskit Terra. This can easily be done with pip/pypi: pip install Cython
.
Compiler Workflow¶
The qiskit.compile()
function has been deprecated and replaced by first calling qiskit.compiler.transpile()
to run optimization and mapping on a circuit, and then qiskit.compiler.assemble()
to build a Qobj from that optimized circuit to send to a backend. While this is only a deprecation it will emit a warning if you use the old qiskit.compile()
call.
transpile(), assemble(), execute() parameters
These functions are heavily overloaded and accept a wide range of inputs. They can handle circuit and pulse inputs. All kwargs except for backend
for these functions now also accept lists of the previously accepted types. The initial_layout
kwarg can now be supplied as a both a list and dictionary, e.g. to map a Bell experiment on qubits 13 and 14, you can supply: initial_layout=[13, 14]
or initial_layout={qr[0]: 13, qr[1]: 14}
Qobj¶
The Qobj class has been split into two separate subclasses depending on the use case, either PulseQobj
or QasmQobj
for pulse and circuit jobs respectively. If you're interacting with Qobj directly you may need to adjust your usage accordingly.
The qiskit.qobj.qobj_to_dict()
is removed. Instead use the to_dict()
method of a Qobj object.
Visualization¶
The largest change to the visualization module is it has moved from qiskit.tools.visualization
to qiskit.visualization
. This was done to indicate that the visualization module is more than just a tool. However, since this interface was declared stable in the 0.7 release the public interface off of qiskit.tools.visualization
will continue to work. That may change in a future release, but it will be deprecated prior to removal if that happens.
The previously deprecated functions, plot_circuit()
, latex_circuit_drawer()
, generate_latex_source()
, and matplotlib_circuit_drawer()
from qiskit.tools.visualization
have been removed. Instead of these functions, calling qiskit.visualization.circuit_drawer()
with the appropriate arguments should be used.
The previously deprecated plot_barriers
and reverse_bits
keys in the style
kwarg dictionary are deprecated, instead the qiskit.visualization.circuit_drawer()
kwargs plot_barriers
and reverse_bits
should be used.
The Wigner plotting functions plot_wigner_function
, plot_wigner_curve
, plot_wigner_plaquette
, and plot_wigner_data
previously in the qiskit.tools.visualization._state_visualization
module have been removed. They were never exposed through the public stable interface and were not well documented. The code to use this feature can still be accessed through the qiskit-tutorials repository.
Mapper¶
The public api from qiskit.mapper
has been moved into qiskit.transpiler
. While it has only been deprecated in this release, it will be removed in the 0.9 release so updating your usage of Layout
and CouplingMap
to import from qiskit.transpiler
instead of qiskit.mapper
before that takes place will avoid any surprises in the future.
Aer 0.2¶
New Features¶
-
Added multiplexer gate #192
-
Added
remap_noise_model
function tonoise.utils
#181 -
Added
__eq__
method toNoiseModel
,QuantumError
,ReadoutError
#181 -
Added support for labelled gates in noise models #175
-
Added optimized
mcx
,mcy
,mcz
,mcu1
,mcu2
,mcu3
, gates toQubitVector
#124 -
Added optimized controlled-swap gate to
QubitVector
#142 -
Added gate-fusion optimization for
QasmController
, which is enabled by settingfusion_enable=true
#136 -
Added better management of failed simulations #167
-
Added qubits truncate optimization for unused qubits #164
-
Added ability to disable depolarizing error on device noise model #131
-
Added initialize simulator instruction to
statevector_state
#117, #137 -
Added coupling maps to simulators #93
-
Added circuit optimization framework #83
-
Added benchmarking #71, #177
-
Added wheels support for Debian-like distributions #69
-
Added autoconfiguration of threads for qasm simulator #61
-
Added Simulation method based on Stabilizer Rank Decompositions #51
-
Added
basis_gates
kwarg toNoiseModel
init #175. -
Added an optional parameter to
NoiseModel.as_dict()
for returning dictionaries that can be serialized using the standard json library directly #165 -
Refactor thread management #50
-
Improve noise transformations #162
-
Improve error reporting #160
-
Improve efficiency of parallelization with
max_memory_mb
a new parameter ofbackend_opts
#61 -
Improve u1 performance in
statevector
#123
Bug Fixes¶
-
Fixed OpenMP clashing problems on macOS for the Terra add-on #46
Compatibility Considerations¶
-
Deprecated
"initial_statevector"
backend option forQasmSimulator
andStatevectorSimulator
#185 -
Renamed
"chop_threshold"
backend option to"zero_threshold"
and changed default value to 1e-10 #185
Ignis 0.1¶
New Features¶
-
Quantum volume
-
Measurement mitigation using tensored calibrations
-
Simultaneous RB has the option to align Clifford gates across subsets
-
Measurement correction can produce a new calibration for a subset of qubits
Compatibility Considerations¶
-
RB writes to the minimal set of classical registers (it used to be Q[i]->C[i]). This change enables measurement correction with RB. Unless users had external analysis code, this will not change outcomes. RB circuits from 0.1 are not compatible with 0.1.1 fitters.
Aqua 0.5¶
New Features¶
-
Implementation of the HHL algorithm supporting
LinearSystemInput
-
Pluggable component
Eigenvalues
with variantEigQPE
-
Pluggable component
Reciprocal
with variantsLookupRotation
andLongDivision
-
Multiple-Controlled U1 and U3 operations
mcu1
andmcu3
-
Pluggable component
QFT
derived from componentIQFT
-
Summarized the transpiled circuits at the DEBUG logging level
-
QuantumInstance
acceptsbasis_gates
andcoupling_map
again. -
Support to use
cx
gate for the entanglement inRY
andRYRZ
variational form (cz
is the default choice) -
Support to use arbitrary mixer Hamiltonian in QAOA, allowing use of QAOA in constrained optimization problems [arXiv:1709.03489]
-
Added variational algorithm base class
VQAlgorithm
, implemented byVQE
andQSVMVariational
-
Added
ising/docplex.py
for automatically generating Ising Hamiltonian from optimization models of DOcplex -
Added
'basic-dirty-ancilla
' mode formct
-
Added
mcmt
for Multi-Controlled, Multi-Target gate -
Exposed capabilities to generate circuits from logical AND, OR, DNF (disjunctive normal forms), and CNF (conjunctive normal forms) formulae
-
Added the capability to generate circuits from ESOP (exclusive sum of products) formulae with optional optimization based on Quine-McCluskey and ExactCover
-
Added
LogicalExpressionOracle
for generating oracle circuits from arbitrary Boolean logic expressions (including DIMACS support) with optional optimization capability -
Added
TruthTableOracle
for generating oracle circuits from truth-tables with optional optimization capability -
Added
CustomCircuitOracle
for generating oracle from user specified circuits -
Added implementation of the Deutsch-Jozsa algorithm
-
Added implementation of the Bernstein-Vazirani algorithm
-
Added implementation of the Simon's algorithm
-
Added implementation of the Shor's algorithm
-
Added optional capability for Grover's algorithm to take a custom initial state (as opposed to the default uniform superposition)
-
Added capability to create a
Custom
initial state using existing circuit -
Added the ADAM (and AMSGRAD) optimization algorithm
-
Multivariate distributions added, so uncertainty models now have univariate and multivariate distribution components
-
Added option to include or skip the swaps operations for qft and iqft circuit constructions
-
Added classical linear system solver
ExactLSsolver
-
Added parameters
auto_hermitian
andauto_resize
toHHL
algorithm to support non-Hermitian and non \(2^n\) sized matrices by default -
Added another feature map,
RawFeatureVector
, that directly maps feature vectors to qubits' states for classification -
SVM_Classical
can now load models trained byQSVM
Bug Fixes¶
-
Fixed
ising/docplex.py
to correctly multiply constant values in constraints -
Fixed package setup to correctly identify namespace packages using
setuptools.find_namespace_packages
Compatibility Considerations¶
-
QuantumInstance
does not takememory
anymore. -
Moved command line and GUI to separate repo (
qiskit_aqua_uis
) -
Removed the
SAT
-specific oracle (now supported byLogicalExpressionOracle
) -
Changed
advanced
mode implementation ofmct
: using simpleh
gates instead ofch
, and fixing the old recursion step in_multicx
-
Components
random_distributions
renamed touncertainty_models
-
Reorganized the constructions of various common gates (
ch
,cry
,mcry
,mct
,mcu1
,mcu3
,mcmt
,logic_and
, andlogic_or
) and circuits (PhaseEstimationCircuit
,BooleanLogicCircuits
,FourierTransformCircuits
, andStateVectorCircuits
) under thecircuits
directory -
Renamed the algorithm
QSVMVariational
toVQC
, which stands for Variational Quantum Classifier -
Renamed the algorithm
QSVMKernel
toQSVM
-
Renamed the class
SVMInput
toClassificationInput
-
Renamed problem type
'svm_classification'
to'classification'
-
Changed the type of
entangler_map
used inFeatureMap
andVariationalForm
to list of lists
IBM Q Provider 0.1¶
New Features¶
-
This is the first release as a standalone package. If you are installing Terra standalone you'll also need to install the
qiskit-ibmq-provider
package withpip install qiskit-ibmq-provider
if you want to use the IBM Q backends. -
Support for non-Qobj format jobs has been removed from the provider. You'll have to convert submissions in an older format to Qobj before you can submit.
Qiskit 0.8¶
In Qiskit 0.8 we introduced the Qiskit Ignis element. It also includes the Qiskit Terra element 0.7.1 release which contains a bug fix for the BasicAer Python simulator.
Ignis 0.1¶
This is the first release of Qiskit Ignis.
Qiskit 0.7¶
In Qiskit 0.7 we introduced Qiskit Aer and combined it with Qiskit Terra.
Terra 0.7¶
New Features¶
This release includes several new features and many bug fixes. With this release the interfaces for circuit diagram, histogram, bloch vectors, and state visualizations are declared stable. Additionally, this release includes a defined and standardized bit order/endianness throughout all aspects of Qiskit. These are all declared as stable interfaces in this release which won't have breaking changes made moving forward, unless there is appropriate and lengthy deprecation periods warning of any coming changes.
There is also the introduction of the following new features:
-
A new ASCII art circuit drawing output mode
-
A new circuit drawing interface off of
QuantumCircuit
objects that enables calls ofcircuit.draw()
orprint(circuit)
to render a drawing of circuits -
A visualizer for drawing the DAG representation of a circuit
-
A new quantum state plot type for hinton diagrams in the local matplotlib based state plots
-
2 new constructor methods off the
QuantumCircuit
classfrom_qasm_str()
andfrom_qasm_file()
which let you easily create a circuit object from OpenQASM -
A new function
plot_bloch_multivector()
to plot Bloch vectors from a tensored state vector or density matrix -
Per-shot measurement results are available in simulators and select devices. These can be accessed by setting the
memory
kwarg toTrue
when callingcompile()
orexecute()
and then accessed using theget_memory()
method on theResult
object. -
A
qiskit.quantum_info
module with revamped Pauli objects and methods for working with quantum states -
New transpile passes for circuit analysis and transformation:
CommutationAnalysis
,CommutationTransformation
,CXCancellation
,Decompose
,Unroll
,Optimize1QGates
,CheckMap
,CXDirection
,BarrierBeforeFinalMeasurements
-
New alternative swap mapper passes in the transpiler:
BasicSwap
,LookaheadSwap
,StochasticSwap
-
More advanced transpiler infrastructure with support for analysis passes, transformation passes, a global
property_set
for the pass manager, and repeat-until control of passes
Compatibility Considerations¶
As part of the 0.7 release the following things have been deprecated and will either be removed or changed in a backwards incompatible manner in a future release. While not strictly necessary these are things to adjust for before the next release to avoid a breaking change.
-
plot_circuit()
,latex_circuit_drawer()
,generate_latex_source()
, andmatplotlib_circuit_drawer()
from qiskit.tools.visualization are deprecated. Instead thecircuit_drawer()
function from the same module should be used, there are kwarg options to mirror the functionality of all the deprecated functions. -
The current default output of
circuit_drawer()
(using latex and falling back on python) is deprecated and will be changed to just use thetext
output by default in future releases. -
The
qiskit.wrapper.load_qasm_string()
andqiskit.wrapper.load_qasm_file()
functions are deprecated and theQuantumCircuit.from_qasm_str()
andQuantumCircuit.from_qasm_file()
constructor methods should be used instead. -
The
plot_barriers
andreverse_bits
keys in thestyle
kwarg dictionary are deprecated, instead theqiskit.tools.visualization.circuit_drawer()
kwargsplot_barriers
andreverse_bits
should be used instead. -
The functions
plot_state()
andiplot_state()
have been depreciated. Instead the functionsplot_state_*()
andiplot_state_*()
should be called for the visualization method required. -
The
skip_transpiler
argument has been deprecated fromcompile()
andexecute()
. Instead you can use thePassManager
directly, just set thepass_manager
to a blankPassManager
object withPassManager()
-
The
transpile_dag()
functionformat
kwarg for emitting different output formats is deprecated, instead you should convert the default outputDAGCircuit
object to the desired format. -
The unrollers have been deprecated, moving forward only DAG to DAG unrolling will be supported.
Please note that some backwards-incompatible changes have been made during this release. The following notes contain information on how to adapt to these changes.
Changes to Result objects¶
As part of the rewrite of the Results object to be more consistent and a stable interface moving forward a few changes have been made to how you access the data stored in the result object. First the get_data()
method has been renamed to just data()
. Accompanying that change is a change in the data format returned by the function. It is now returning the raw data from the backends instead of doing any post-processing. For example, in previous versions you could call:
result = execute ( circuit , backend ) . result () unitary = result . get_data ()[ 'unitary' ] print ( unitary )
and that would return the unitary matrix like:
[[ 1 + 0 j , 0 + 0.5 j ], [ 0 - 0.5 j ][ - 1 + 0 j ]]
But now if you call (with the renamed method):
it will return something like:
[[[ 1 , 0 ], [ 0 , - 0.5 ]], [[ 0 , - 0.5 ], [ - 1 , 0 ]]]
To get the post processed results in the same format as before the 0.7 release you must use the get_counts()
, get_statevector()
, and get_unitary()
methods on the result object instead of get_data()['counts']
, get_data()['statevector']
, and get_data()['unitary']
respectively.
Additionally, support for len()
and indexing on a Result
object has been removed. Instead you should deal with the output from the post processed methods on the Result objects.
Also, the get_snapshot()
and get_snapshots()
methods from the Result
class have been removed. Instead you can access the snapshots using Result.data()['snapshots']
.
Changes to Visualization¶
The largest change made to visualization in the 0.7 release is the removal of Matplotlib and other visualization dependencies from the project requirements. This was done to simplify the requirements and configuration required for installing Qiskit. If you plan to use any visualizations (including all the jupyter magics) except for the text
, latex
, and latex_source
output for the circuit drawer you'll you must manually ensure that the visualization dependencies are installed. You can leverage the optional requirements to the Qiskit Terra package to do this:
pip install qiskit - terra [ visualization ]
Aside from this there have been changes made to several of the interfaces as part of the stabilization which may have an impact on existing code. The first is the basis
kwarg in the circuit_drawer()
function is no longer accepted. If you were relying on the circuit_drawer()
to adjust the basis gates used in drawing a circuit diagram you will have to do this priort to calling circuit_drawer()
. For example:
from qiskit.tools import visualization visualization . circuit_drawer ( circuit , basis_gates = 'x,U,CX' )
will have to be adjusted to be:
from qiskit import BasicAer from qiskit import transpiler from qiskit.tools import visualization backend = BasicAer . backend ( 'qasm_simulator' ) draw_circ = transpiler . transpile ( circuit , backend , basis_gates = 'x,U,CX' ) visualization . circuit_drawer ( draw_circ )
Moving forward the circuit_drawer()
function will be the sole interface for circuit drawing in the visualization module. Prior to the 0.7 release there were several other functions which either used different output backends or changed the output for drawing circuits. However, all those other functions have been deprecated and that functionality has been integrated as options on circuit_drawer()
.
For the other visualization functions, plot_histogram()
and plot_state()
there are also a few changes to check when upgrading. First is the output from these functions has changed, in prior releases these would interactively show the output visualization. However that has changed to instead return a matplotlib.Figure
object. This provides much more flexibility and options to interact with the visualization prior to saving or showing it. This will require adjustment to how these functions are consumed. For example, prior to this release when calling:
plot_histogram ( counts ) plot_state ( rho )
would open up new windows (depending on matplotlib backend) to display the visualization. However starting in the 0.7 you'll have to call show()
on the output to mirror this behavior. For example:
plot_histogram ( counts ) . show () plot_state ( rho ) . show ()
or:
hist_fig = plot_histogram ( counts ) state_fig = plot_state ( rho ) hist_fig . show () state_fig . show ()
Note that this is only for when running outside of Jupyter. No adjustment is required inside a Jupyter environment because Jupyter notebooks natively understand how to render matplotlib.Figure
objects.
However, returning the Figure object provides additional flexibility for dealing with the output. For example instead of just showing the figure you can now directly save it to a file by leveraging the savefig()
method. For example:
hist_fig = plot_histogram ( counts ) state_fig = plot_state ( rho ) hist_fig . savefig ( 'histogram.png' ) state_fig . savefig ( 'state_plot.png' )
The other key aspect which has changed with these functions is when running under jupyter. In the 0.6 release plot_state()
and plot_histogram()
when running under jupyter the default behavior was to use the interactive Javascript plots if the externally hosted Javascript library for rendering the visualization was reachable over the network. If not it would just use the matplotlib version. However in the 0.7 release this no longer the case, and separate functions for the interactive plots, iplot_state()
and iplot_histogram()
are to be used instead. plot_state()
and plot_histogram()
always use the matplotlib versions.
Additionally, starting in this release the plot_state()
function is deprecated in favor of calling individual methods for each method of plotting a quantum state. While the plot_state()
function will continue to work until the 0.9 release, it will emit a warning each time it is used. The
Qiskit Terra 0.6 | Qiskit Terra 0.7+ |
---|---|
plot_state(rho) | plot_state_city(rho) |
plot_state(rho, method='city') | plot_state_city(rho) |
plot_state(rho, method='paulivec') | plot_state_paulivec(rho) |
plot_state(rho, method='qsphere') | plot_state_qsphere(rho) |
plot_state(rho, method='bloch') | plot_bloch_multivector(rho) |
plot_state(rho, method='hinton') | plot_state_hinton(rho) |
The same is true for the interactive JS equivalent, iplot_state()
. The function names are all the same, just with a prepended i for each function. For example, iplot_state(rho, method='paulivec')
is iplot_state_paulivec(rho)
.
Changes to Backends¶
With the improvements made in the 0.7 release there are a few things related to backends to keep in mind when upgrading. The biggest change is the restructuring of the provider instances in the root qiskit`
namespace. The Aer
provider is not installed by default and requires the installation of the qiskit-aer
package. This package contains the new high performance fully featured simulator. If you installed via pip install qiskit
you'll already have this installed. The python simulators are now available under qiskit.BasicAer
and the old C++ simulators are available with qiskit.LegacySimulators
. This also means that the implicit fallback to python based simulators when the C++ simulators are not found doesn't exist anymore. If you ask for a local C++ based simulator backend, and it can't be found an exception will be raised instead of just using the python simulator instead.
Additionally the previously deprecation top level functions register()
and available_backends()
have been removed. Also, the deprecated backend.parameters()
and backend.calibration()
methods have been removed in favor of backend.properties()
. You can refer to the 0.6 release notes section Working with backends for more details on these changes.
The backend.jobs()
and backend.retrieve_jobs()
calls no longer return results from those jobs. Instead you must call the result()
method on the returned jobs objects.
Changes to the compiler, transpiler, and unrollers¶
As part of an effort to stabilize the compiler interfaces there have been several changes to be aware of when leveraging the compiler functions. First it is important to note that the qiskit.transpiler.transpile()
function now takes a QuantumCircuit object (or a list of them) and returns a QuantumCircuit object (or a list of them). The DAG processing is done internally now.
You can also easily switch between circuits, DAGs, and Qobj now using the functions in qiskit.converters
.
Aer 0.1¶
New Features¶
Aer provides three simulator backends:
-
QasmSimulator
: simulate experiments and return measurement outcomes -
StatevectorSimulator
: return the final statevector for a quantum circuit acting on the all zero state -
UnitarySimulator
: return the unitary matrix for a quantum circuit
noise
module: contains advanced noise modeling features for the QasmSimulator
-
NoiseModel
,QuantumError
,ReadoutError
classes for simulating a Qiskit quantum circuit in the presence of errors -
errors
submodule including functions for generatingQuantumError
objects for the following types of quantum errors: Kraus, mixed unitary, coherent unitary, Pauli, depolarizing, thermal relaxation, amplitude damping, phase damping, combined phase and amplitude damping -
device
submodule for automatically generating a noise model based on theBackendProperties
of a device
utils
module:
-
qobj_utils
provides functions for directly modifying a Qobj to insert special simulator instructions not yet supported through the Qiskit Terra API.
Aqua 0.4¶
New Features¶
-
Programmatic APIs for algorithms and components – each component can now be instantiated and initialized via a single (non-empty) constructor call
-
QuantumInstance
API for algorithm/backend decoupling –QuantumInstance
encapsulates a backend and its settings -
Updated documentation and Jupyter Notebooks illustrating the new programmatic APIs
-
Transparent parallelization for gradient-based optimizers
-
Multiple-Controlled-NOT (cnx) operation
-
Pluggable algorithmic component
RandomDistribution
-
Concrete implementations of
RandomDistribution
:BernoulliDistribution
,LogNormalDistribution
,MultivariateDistribution
,MultivariateNormalDistribution
,MultivariateUniformDistribution
,NormalDistribution
,UniformDistribution
, andUnivariateDistribution
-
Concrete implementations of
UncertaintyProblem
:FixedIncomeExpectedValue
,EuropeanCallExpectedValue
, andEuropeanCallDelta
-
Amplitude Estimation algorithm
-
Qiskit Optimization: New Ising models for optimization problems exact cover, set packing, vertex cover, clique, and graph partition
-
Qiskit AI:
-
New feature maps extending the
FeatureMap
pluggable interface:PauliExpansion
andPauliZExpansion
-
Training model serialization/deserialization mechanism
-
-
Qiskit Finance:
-
Amplitude estimation for Bernoulli random variable: illustration of amplitude estimation on a single qubit problem
-
Loading of multiple univariate and multivariate random distributions
-
European call option: expected value and delta (using univariate distributions)
-
Fixed income asset pricing: expected value (using multivariate distributions)
-
-
The Pauli string in
Operator
class is aligned with Terra 0.7. Now the order of a n-qubit pauli string isq_{n-1}...q{0}
Thus, the (de)serialier (save_to_dict
andload_from_dict
) in theOperator
class are also changed to adopt the changes ofPauli
class.
Compatibility Considerations¶
-
HartreeFock
component of pluggable typeInitialState
moved to Qiskit Chemistry -
UCCSD
component of pluggable typeVariationalForm
moved to Qiskit Chemistry
Qiskit 0.6¶
Terra 0.6¶
Highlights¶
This release includes a redesign of internal components centered around a new, formal communication format (Qobj), along with long awaited features to improve the user experience as a whole. The highlights, compared to the 0.5 release, are:
-
Improvements for inter-operability (based on the Qobj specification) and extensibility (facilities for extending Qiskit with new backends in a seamless way)
-
New options for handling credentials and authentication for the IBM Q backends, aimed at simplifying the process and supporting automatic loading of user credentials
-
A revamp of the visualization utilities: stylish interactive visualizations are now available for Jupyter users, along with refinements for the circuit drawer (including a matplotlib-based version)
-
Performance improvements centered around circuit transpilation: the basis for a more flexible and modular architecture have been set, including parallelization of the circuit compilation and numerous optimizations
Compatibility Considerations¶
Please note that some backwards-incompatible changes have been introduced during this release – the following notes contain information on how to adapt to the new changes.
Removal of QuantumProgram
¶
As hinted during the 0.5 release, the deprecation of the QuantumProgram
class has now been completed and is no longer available, in favor of working with the individual components ( BaseJob
, QuantumCircuit
, ClassicalRegister
, QuantumRegister
, qiskit
) directly.
Please check the 0.5 release notes and the examples for details about the transition:
from qiskit import QuantumCircuit , ClassicalRegister , QuantumRegister from qiskit import Aer , execute q = QuantumRegister ( 2 ) c = ClassicalRegister ( 2 ) qc = QuantumCircuit ( q , c ) qc . h ( q [ 0 ]) qc . cx ( q [ 0 ], q [ 1 ]) qc . measure ( q , c ) backend = get_backend ( 'qasm_simulator' ) job_sim = execute ( qc , backend ) sim_result = job_sim . result () print ( "simulation: " , sim_result ) print ( sim_result . get_counts ( qc ))
IBM Q Authentication and Qconfig.py
¶
The managing of credentials for authenticating when using the IBM Q backends has been expanded, and there are new options that can be used for convenience:
-
save your credentials in disk once, and automatically load them in future sessions. This provides a one-off mechanism:
from qiskit import IBMQ IBMQ . save_account ( 'MY_API_TOKEN' , 'MY_API_URL' )
afterwards, your credentials can be automatically loaded from disk by invoking
load_accounts()
:from qiskit import IBMQ IBMQ . load_accounts ()
or you can load only specific accounts if you only want to use those in a session:
IBMQ . load_accounts ( project = 'MY_PROJECT' )
-
use environment variables. If
QE_TOKEN
andQE_URL
is set, theIBMQ.load_accounts()
call will automatically load the credentials from them.
Additionally, the previous method of having a Qconfig.py
file in the program folder and passing the credentials explicitly is still supported.
Working with backends¶
A new mechanism has been introduced in Terra 0.6 as the recommended way for obtaining a backend, allowing for more powerful and unified filtering and integrated with the new credentials system. The previous top-level methods register()
, available_backends()
and get_backend()
are still supported, but will deprecated in upcoming versions in favor of using the qiskit.IBMQ and qiskit.Aer objects directly, which allow for more complex filtering.
For example, to list and use a local backend:
from qiskit import Aer all_local_backends = Aer . backends ( local = True ) # returns a list of instances qasm_simulator = Aer . backends ( 'qasm_simulator' )
And for listing and using remote backends:
from qiskit import IBMQ IBMQ . enable_account ( 'MY_API_TOKEN' ) 5 _qubit_devices = IBMQ . backends ( simulator = True , n_qubits = 5 ) ibmqx4 = IBMQ . get_backend ( 'ibmqx4' )
Please note as well that the names of the local simulators have been simplified. The previous names can still be used, but it is encouraged to use the new, shorter names:
Qiskit Terra 0.5 | Qiskit Terra 0.6 |
---|---|
'local_qasm_simulator' | 'qasm_simulator' |
'local_statevector_simulator' | 'statevector_simulator' |
'local_unitary_simulator_py' | 'unitary_simulator' |
Backend and Job API changes¶
-
Jobs submitted to IBM Q backends have improved capabilities. It is possible to cancel them and replenish credits (
job.cancel()
), and to retrieve previous jobs executed on a specific backend either by job id (backend.retrieve_job(job_id)
) or in batch of latest jobs (backend.jobs(limit)
) -
Properties for checking each individual job status (
queued
,running
,validating
,done
andcancelled
) no longer exist. If you want to check the job status, use the identity comparison againstjob.status
:from qiskit.backends import JobStatus job = execute ( circuit , backend ) if job . status () is JobStatus . RUNNING : handle_job ( job )
Please consult the new documentation of the IBMQJob
class to get further insight in how to use the simplified API.
-
A number of members of
BaseBackend
andBaseJob
are no longer properties, but methods, and as a result they need to be invoked as functions.Qiskit Terra 0.5
Qiskit Terra 0.6
backend.name
backend.name()
backend.status
backend.status()
backend.configuration
backend.configuration()
backend.calibration
backend.properties()
backend.parameters
backend.jobs() backend.retrieve_job(job_id)
job.status
job.status()
job.cancelled
job.queue_position()
job.running
job.cancel()
job.queued
job.done
Qiskit 0.5¶
Terra 0.5¶
Highlights¶
This release brings a number of improvements to Qiskit, both for the user experience and under the hood. Please refer to the full changelog for a detailed description of the changes - the highlights are:
-
new
statevector
simulators
and feature and performance improvements to the existing ones (in particular to the C++ simulator), along with a reorganization of how to work with backends focused on extensibility and flexibility (using aliases and backend providers) -
reorganization of the asynchronous features, providing a friendlier interface for running jobs asynchronously via
Job
instances -
numerous improvements and fixes throughout the Terra as a whole, both for convenience of the users (such as allowing anonymous registers) and for enhanced functionality (such as improved plotting of circuits)
Compatibility Considerations¶
Please note that several backwards-incompatible changes have been introduced during this release as a result of the ongoing development. While some of these features will continue to be supported during a period of time before being fully deprecated, it is recommended to update your programs in order to prepare for the new versions and take advantage of the new functionality.
QuantumProgram
changes¶
Several methods of the QuantumProgram
class are on their way to being deprecated:
-
methods for interacting with the backends and the API:
The recommended way for opening a connection to the IBM Q API and for using the backends is through the top-level functions directly instead of the
QuantumProgram
methods. In particular, theqiskit.register()
method provides the equivalent of the previousqiskit.QuantumProgram.set_api()
call. In a similar vein, there is a newqiskit.available_backends()
,qiskit.get_backend()
and related functions for querying the available backends directly. For example, the following snippet for version 0.4:from qiskit import QuantumProgram quantum_program = QuantumProgram () quantum_program . set_api ( token , url ) backends = quantum_program . available_backends () print ( quantum_program . get_backend_status ( 'ibmqx4' )
would be equivalent to the following snippet for version 0.5:
from qiskit import register , available_backends , get_backend register ( token , url ) backends = available_backends () backend = get_backend ( 'ibmqx4' ) print ( backend . status )
-
methods for compiling and executing programs:
The top-level functions now also provide equivalents for the
qiskit.QuantumProgram.compile()
andqiskit.QuantumProgram.execute()
methods. For example, the following snippet from version 0.4:quantum_program . execute ( circuit , args , ... )
would be equivalent to the following snippet for version 0.5:
from qiskit import execute execute ( circuit , args , ... )
In general, from version 0.5 onwards we encourage to try to make use of the individual objects and classes directly instead of relying on QuantumProgram
. For example, a QuantumCircuit
can be instantiated and constructed by appending QuantumRegister
, ClassicalRegister
, and gates directly. Please check the update example in the Quickstart section, or the using_qiskit_core_level_0.py
and using_qiskit_core_level_1.py
examples on the main repository.
Backend name changes¶
In order to provide a more extensible framework for backends, there have been some design changes accordingly:
-
local simulator names
The names of the local simulators have been homogenized in order to follow the same pattern:
PROVIDERNAME_TYPE_simulator_LANGUAGEORPROJECT
- for example, the C++ simulator previously namedlocal_qiskit_simulator
is nowlocal_qasm_simulator_cpp
. An overview of the current simulators:-
QASM
simulator is supposed to be like an experiment. You apply a circuit on some qubits, and observe measurement results - and you repeat for many shots to get a histogram of counts viaresult.get_counts()
. -
Statevector
simulator is to get the full statevector (\(2^n\) amplitudes) after evolving the zero state through the circuit, and can be obtained viaresult.get_statevector()
. -
Unitary
simulator is to get the unitary matrix equivalent of the circuit, returned viaresult.get_unitary()
. -
In addition, you can get intermediate states from a simulator by applying a
snapshot(slot)
instruction at various spots in the circuit. This will save the current state of the simulator in a given slot, which can later be retrieved viaresult.get_snapshot(slot)
.
-
-
backend aliases:
The SDK now provides an "alias" system that allows for automatically using the most performant simulator of a specific type, if it is available in your system. For example, with the following snippet:
from qiskit import get_backend backend = get_backend ( 'local_statevector_simulator' )
the backend will be the C++ statevector simulator if available, falling back to the Python statevector simulator if not present.
More flexible names and parameters¶
Several functions of the SDK have been made more flexible and user-friendly:
-
automatic circuit and register names
qiskit.ClassicalRegister
,qiskit.QuantumRegister
andqiskit.QuantumCircuit
can now be instantiated without explicitly giving them a name - a new autonaming feature will automatically assign them an identifier:Please note as well that the order of the parameters have been swapped
QuantumRegister(size, name)
. -
methods accepting names or instances
In combination with the autonaming changes, several methods such as
qiskit.Result.get_data()
now accept both names and instances for convenience. For example, when retrieving the results for a job that has a single circuit such as:qc = QuantumCircuit ( ... , name = 'my_circuit' ) job = execute ( qc , ... ) result = job . result ()
The following calls are equivalent:
data = result . get_data ( 'my_circuit' ) data = result . get_data ( qc ) data = result . get_data ()
Raw Write() Returned Invalid Length 110 (Should Have Been Between 0 and 55)
Source: https://qiskit.org/documentation/release_notes.html
0 Response to "Raw Write() Returned Invalid Length 110 (Should Have Been Between 0 and 55)"
Post a Comment