Qiskit 0.23 release notes
0.23.6
Terra 0.16.4
No change
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.
Ignis 0.5.2
No change
Aqua 0.8.2
No change
IBM Q Provider 0.11.1
No change
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_codesmodule 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
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
Aer 0.7.3
No change
Ignis 0.5.1
No change
Aqua 0.8.1
No change
IBM Q Provider 0.11.1
No change
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
MCXGrayCodewill now create aC3XGateifnum_ctrl_qubitsis 3 and aC4XGateifnum_ctrl_qubitsis 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_bitsis 1, aCXGateis created, and if 2, aCCXGateis created.
Bug Fixes
-
Pulse
Delayinstructions are now explicitly assembled asPulseQobjInstructionobjects included in thePulseQobjoutput fromassemble().Previously, we could ignore
Delayinstructions in aScheduleas part ofassemble()as the time was explicit in thePulseQobjobjects. 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
BasisTranslatorandUnrollerpasses, 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_phasewas set a factor of was missing from the appended phase. -
Fix the global phase of the output of the
QuantumCircuitmethodrepeat(). 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
SparsePauliOpwhere 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 to 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))<class 'list'> 1
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
QasmSimulatorbasis 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_gateswas 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.
Ignis 0.5.1
No change
Aqua 0.8.1
No change
IBM Q Provider 0.11.1
No change
0.23.2
Terra 0.16.1
No change
Aer 0.7.2
New Features
- Add the CMake flag
DISABLE_CONAN(default=``OFF``)s. When installing from source, setting this toONallows 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.
Ignis 0.5.1
No change
Aqua 0.8.1
No change
IBM Q Provider 0.11.1
No change
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 where was an
Operatorobject. 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
AerProviderwhere 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
SXGatewas 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, andProcessTomographyFitterto 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_stateparameter inQAOAhas now different implementation as a result of a bug fix. The previous implementation wrongly mixed the user providedinitial_statewith Hadamard gates. The issue is fixed now. No attention needed if your code does not make use of the user providedinitial_stateparameter.
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_symbolhas been removed from theVarTypein 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-community/qiskit-aqua/issues/1311> for more details.
- Trotter class did not use the reps argument in constructor. #1317 <https://github.com/qiskit-community/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-community/qiskit-aqua/issues/1321> for more details.
to_opflow()returns a correct operator when coefficients are complex numbers. #1381 <https://github.com/qiskit-community/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
transpilemethod by calling itsrunmethod if it exists. - A bug that mixes custom
initial_stateinQAOAwith 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_stateparameter 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.Experimentnow 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 alimitparameter that allows you to limit the number of experiments and analysis results returned.
Upgrade Notes
- A new parameter,
limitis now the first parameter for bothqiskit.providers.ibmq.experiment.ExperimentService.experiments()andqiskit.providers.ibmq.experiment.ExperimentService.analysis_results()methods. Thislimithas 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
CREATINGstate if job submit fails half-way through. - Fixes the infinite loop raised when passing an
IBMQRandomServiceinstance to a child process.
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 theQuantumCircuitclass has been extended through thetranspiler,quantum_info, andassemblermodules, 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 theGRgate, and global Rz (GRZ) that is defined in a similar way to theGRgates. 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
QuantumCircuiton aQuantumRegisterof 3 qubits and perform aRGateof an angle about an axis in the xy-plane of the Bloch spheres that makes an angle of with the x-axis on each qubit. -
A new color scheme,
iqx, has been added to themplbackend 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
~/.qiskitdirectory, in the filesettings.confunder the[Default]heading, a user can entercircuit_mpl_style = iqxto select theiqxcolor scheme.The second way is to add
{'name': 'iqx'}to thestylekwarg to theQuantumCircuit.drawmethod or to thecircuit_drawerfunction. 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
stylekwarg for the the circuit drawerqiskit.visualization.circuit_drawer()andqiskit.circuit.QuantumCircuit.draw()thedisplaycolorfield with themplbackend 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 thegatetextcolorfield will be used. Gate colors can be set in thestyledict for any number of gate types, from one to the entiredisplaycolordict. 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_delayparameter has been added to theQasmQobjclass 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 theBackendConfigurationmethodrep_delay_range(). If a value is not provided a backend default,qiskit.providers.models.BackendConfiguration.default_rep_delay, will be used.rep_delaywill only work on backends which allow for dynamic repetition time. This is can be checked with theBackendConfigurationpropertydynamic_reprate_enabled. -
The
qobj_schema.jsonJSON Schema file inqiskit.schemashas been updated to include therep_delayas an optional configuration property for QASM Qobjs. -
The
backend_configuration_schema.jsonJSON Schema file inqiskit.schemashas been updated to includedynamic_reprate_enabled,rep_delay_rangeanddefault_rep_delayas optional properties for a QASM backend configuration payload. -
A new optimization pass,
qiskit.transpiler.passes.TemplateOptimizationhas 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
BackendV1methodrun()can now take aQuantumCircuitorScheduleobject as inputs instead ofQobjobjects. 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.JobV1can 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 theJobV1abstract 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, forResultobject input. This parameter does not have any effect for an inputdictorCountsobject. -
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 typeInt1at the moment) intoQuantumCircuitobjects. 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()The parameter
registerless=Falsein theqiskit.circuit.classicalfunction.ClassicalFunctionmethodsynth()creates a circuit with registers refering to the parameter names. For example:quantum_circuit = grover_oracle.synth(registerless=False) quantum_circuit.draw()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()The
GROVER_ORACLEgate is synthesized when its decomposition is required.circuit.decompose().draw()The feature requires
tweedledum, a library for synthesizing quantum circuits, that can be installed via pip withpip install tweedledum. -
A new class
qiskit.circuit.Delayfor 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() -
A new argument
scheduling_methodforqiskit.compiler.transpile()has been added. It is required when transpiling circuits with delays. Ifscheduling_methodis 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)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 aScheduleto 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_path2Refer to the release notes and documentation for
transpile()andsequence()for the details on the other path. -
Added the
GroverOperatorto 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,GroverOperatorcreates the textbook Grover operator. To generalize this for amplitude amplification and use a generic operator instead of Hadamard gates as state preparation, thestate_inargument can be used. -
The
InstructionScheduleMapmethodsget()andpop()methods now takeParameterExpressioninstances 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
LinearAmplitudeFunctionwas added to the circuit library (qiskit.circuit.library) for mapping (piecewise) linear functions on qubit amplitudes,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_outputhas been added to theqiskit.tools.jupytermodule. 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 existingOptimize1qGatesthat uses theOneQubitEulerDecomposerclass to decompose and simplify a chain of single qubit gates. This method is compatible with any basis set, whileOptimize1qGatesonly works for u1, u2, and u3. The default pass managers foroptimization_level1, 2, and 3 have been updated to use this new pass if the basis set doesn’t include u1, u2, or u3. -
The
OneQubitEulerDecomposernow supports two new basis,'PSX'and'U'. These can be specified with thebasiskwarg on the constructor. This will decompose the matrix into a circuit usingPGateandSXGatefor'PSX', andUGatefor'U'. -
A new method
remove()has been added to theqiskit.transpiler.PassManagerclass. This method enables removing a pass from aPassManagerinstance. It works on indexes, similar toreplace(). For example, to remove theRemoveResetInZeroStatepass 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, CXCancellationThe stage
[1]withRemoveResetInZeroStatecan 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, andLogNormalDistributionwere 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
QuantumCircuitclass. This enables aQuantumCircuitto override (for basis gates) or specify (for standard and custom gates) a definition of aGateoperation 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
QuantumCircuitmethodadd_calibration()which takes aScheduledefinition 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 gatePreviously, 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
Scheduleby 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
PulseQobjobjects 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_typehas 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_typekwarg is set to'spherical'the list of parameters taken in are of the form[r, theta, phi]whereris the radius,thetais the inclination from +z direction, andphiis 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
Scheduleobjects now support usingParameterExpressionobjects 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.visualizationmodule.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
paramskwarg of the constructor for theGateclass and its subclasses has been changed. Previously allGateparameters had to be in a set of allowed types defined in theInstructionclass. 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,UnitaryGateaccepts a parameter of the typenumpy.ndarrayand 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. IfUnitaryGatewere to be used as parent for a new class, thisvalidate_parametermethod would be used unless the new child class defines its own method. -
The previously deprecated methods, arguments, and properties named
n_qubitsandnumberofqubitshave been removed. These were deprecated in the 0.13.0 release. The full set of changes are:Class Old New QuantumCircuitn_qubitsnum_qubitsPaulinumberofqubitsnum_qubitsFunction Old Argument New Argument qiskit.circuit.random.random_circuit()n_qubitsnum_qubitsqiskit.circuit.library.MSGaten_qubitsnum_qubits -
Inserting a parameterized
Gateinstance into aQuantumCircuitnow 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 parameterizedGateobject into multiple circuits. -
The function
qiskit.result.marginal_counts()now, by default, does not modify theqiskit.result.Resultinstance parameter. Previously, theResultobject was always modified in place. A new kwarginplacehas been addedmarginal_counts()which enables using the previous behavior wheninplace=Trueis set. -
The
U3Gatedefinition has been changed to be in terms of theUGateclass. TheUGateclass 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
PulseBackendConfigurationin thehamiltonianattributes thevarsfield 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
DAGNodeconstructor has been removed. Using a dictonary for the first positional argument was deprecated in the 0.13.0 release. To create aDAGNodeobject 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.standardhas been removed. This module has been deprecated since the 0.14.0 release. Theqiskit.circuit.librarycan be used instead. Additionally, all the gate classes previously inqiskit.extensions.standardare still importable fromqiskit.extensions. -
The previously deprecated gates in the module
qiskit.extensions.quantum_initializer:DiagGate, UCG`,UCPauliRotGate,UCRot,UCRXGate,UCX,UCRYGate,UCY,UCRZGate,UCZhave 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.QuantumCircuitgate 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.ndarrayfor a parameter in theparamskwarg for the constructor of theGateclass and subclasses has been deprecated and will be removed in future releases. This was done as part of the refactoring of howparmstype checking is handled for theGateclass. If you have a custom gate class which is a subclass ofGatedirectly (or via a different parent in the hierarchy) that accepts anndarrayparameter, 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_qubitsproperty of thePiecewiseLinearPauliRotationsandPolynomialPauliRotationsclasses has been deprecated and will be removed in a future release. Instead the propertynum_ancillasshould be used instead. This was done to make it consistent with theQuantumCircuitmethodnum_ancillas(). -
The
qiskit.circuit.library.MSGateclass has been deprecated, but will remain in place to allow loading of old jobs. It has been replaced with theqiskit.circuit.library.GMSclass which should be used instead. -
The
MSBasisDecomposertranspiler pass has been deprecated and will be removed in a future release. Theqiskit.transpiler.passes.BasisTranslatorpass can be used instead. -
The
QuantumCircuitmethodsu1,u2andu3are 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,U2GateandU3Gateremain, to allow loading of old jobs.
Bug Fixes
- The
Resultclass’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 aQuantumCircuitorScheduleinstance, when more than one entry matching the instance name is present in theResultobject. Note that only the first entry matching this name will be returned. Fixes #3207 - The
qiskit.circuit.QuantumCircuitmethodappend()can now be used to insert one parameterized gate instance into multiple circuits. This fixes a previous issue where inserting a single parameterizedGateobject 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 thebackendandpass_managerkwargs to be specified at the same time. This has been fixed so that bothbackendandpass_managercan be used together on calls toexecute(). Fixes #5037 - The
QuantumCircuitmethodunitary()method has been fixed to accept a single integer for theqargargument (when adding a 1-qubit unitary). The allowed types for theqargsargument are nowint,Qubit, or a list of integers. Fixes #4944 - Previously, calling
inverse()on aBlueprintCircuitobject 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.Countsobject from an empty data dictionary. Now this will create an emptyCountsobject. 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_stateof aUnitaryGatewould be applied twice; once in the creation of the matrix for the controlled unitary and again when calling thedefinition()method of theqiskit.circuit.ControlledGateclass. This would give the appearence that settingctrl_statehad no effect. - Previously the
ControlledGatemethodinverse()would not preserve thectrl_stateparameter in some cases. This has been fixed so that callinginverse()will preserve the valuectrl_statein its output. - Fixed a bug in the
mploutput backend of the circuit drawerqiskit.circuit.QuantumCircuit.draw()andqiskit.visualization.circuit_drawer()that would cause the drawer to fail if thestylekwarg 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, orsxdggate 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.Delayinstruction 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.UGateto 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.PhaseGateto 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.CPhaseGateto 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.MCPhaseGateto theStatevectorSimulator,UnitarySimulator, and the"statevector"method of theQasmSimulator. -
Adds support for the gate
qiskit.circuit.library.SXGateto theStatevectorSimulator,UnitarySimulator, andQasmSimulator. -
Adds support for 1 and 2-qubit Qiskit circuit library rotation gates
RXGate,RYGate,RZGate,RGate,RXXGate,RYYGate,RZZGate,RZXGateto 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
QasmSimulatorandPulseSimulatorcan also be configured from anIBMQBackendbackend object using the :meth:`~qiskit.providers.aer.QasmSimulator.from_backend method. For theQasmSimulatorthis will configure the coupling map, basis gates, and basic device noise model based on the backend configuration and properties. For thePulseSimulatorthe 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
PulseSimulatorinstance 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, thePulseSimulatoris 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 fromFakeArmonkwill 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
QasmSimulatorif 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
QauntumErrorgate errors in theNoiseModelto the"matrix_product_state"method of theQasmSimulator. -
Adds support for density matrix snapshot instruction
qiskit.providers.aer.extensions.SnapshotDensityMatrixto 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
StatevectorSimulatorby 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
StatevectorSimulatorandQasmSimulator.For the
"density_matrix"method of theQasmSimulatorand for theUnitarySimulatorgate fusion will be applied to circuits with more than 7 qubits.Custom qubit threshold values can be set using the
fusion_thresholdbackend option iebackend.set_options(fusion_threshold=10) -
Changes
fusion_thresholdbackend 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
variancekwarg 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
StatevectorSimulatorthat 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
StatevectorSimulatorandUnitarySimulator. 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.CNOTDihedralhas 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.CNOTDihedralnow 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.ExpvalMeasMitigatorFitterclass. 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()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)) -
Adds Numba as an optional dependency. Numba is used to significantly increase the performance of the
qiskit.ignis.mitigation.CTMPExpvalMeasMitigatorclass 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.QVFittermethodplot_qv_data()has been updated to return amatplotlib.Figureobject. Previously, it would not return anything. By returning a figure this makes it easier to integrate the visualizations into a largermatplotlibworkflow. -
The error bars in the figure produced by the
qiskit.ignis.verification.QVFittermethodqiskit.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,
figsizehas been added to theqiskit.ignis.verification.QVFittermethodqiskit.ignis.verification.QVFitter.plot_qv_data(). This kwarg takes in a tuple of the form(x, y)wherexandyare 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.CNOTDihedralfor 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
QuantumCircuitobjects as inputs to specify the A- and Q operators. This change goes along with the introduction of theGroverOperatorin 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 be a real number in which specifies the fraction of best observed samples which are used to compute the objective function. Observe that if , CVaR is equivalent to a standard expectation value. Similarly, if , then CVaR corresponds to using the best observed sample. Intermediate values of 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
Eigensolverfor 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
Driverwhich provides the relevant information about the molecule, aTransformationwhich 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. TheQEOMandNumpyEigensolverare 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
OrbitalOptimizationVQEhas 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,GaussianConditionalIndependenceModelandEuropeanCallExpectedValuetoqiskit.finance.applications. -
Gradient Framework.
qiskit.operators.gradientsGiven 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 resp. resp. .
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 resp. resp. resp. .
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 .
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) . 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
transformationsfor the fermionic and bosonic transformation of a problem instance. Transforms the fermionic operator to qubit operator. Respective class for the transformation isfermionic_transformationIntroduces in algorithmsground_state_solversfor the calculation of ground state properties. The calculation can be done either using anMinimumEigensolveror usingAdaptVQEIntroduceschemistry/resultswhere the eigenstate_result and the electronic_structure_result are also used for the algorithms. Introduces Minimum Eigensolver factoriesminimum_eigensolver_factorieswhere chemistry specific minimum eigensolvers can be initialized Introduces orbital optimization vqeoovqeas a ground state solver for chemistry applications -
New Algorithm result classes:
Grovermethod_run()returns classGroverResult.AmplitudeEstimationmethod_run()returns classAmplitudeEstimationResult.IterativeAmplitudeEstimationmethod_run()returns classIterativeAmplitudeEstimationResult.MaximumLikelihoodAmplitudeEstimationmethod_run()returns classMaximumLikelihoodAmplitudeEstimationResult.All new result classes are backwards compatible with previous result dictionary.
-
New Linear Solver result classes:
HHLmethod_run()returns classHHLResult.NumPyLSsolvermethod_run()returns classNumPyLSsolverResult.All new result classes are backwards compatible with previous result dictionary.
-
MinimumEigenOptimizationResultnow exposes properties:samplesandeigensolver_result. The latter is obtained from the underlying algorithm used by the optimizer and specific to the algorithm.RecursiveMinimumEigenOptimizernow returns an instance of the result classRecursiveMinimumEigenOptimizationResultwhich in turn may contains intermediate results obtained from the underlying algorithms. The dedicated result class exposes propertiesreplacementsandhistorythat are specific to this optimizer. The depth of the history is managed by thehistoryparameter of the optimizer. -
GroverOptimizernow returns an instance ofGroverOptimizationResultand this result class exposes propertiesoperation_counts,n_input_qubits, andn_output_qubitsdirectly. These properties are not available in theraw_resultsdictionary anymore. -
SlsqpOptimizernow returns an instance ofSlsqpOptimizationResultand this result class exposes additional properties specific to the SLSQP implementation. -
Support passing
QuantumCircuitobjects 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
evalon state function objects with no argument, which returns theVectorStateFnrepresentation of the state function. This is consistent behavior withOperatorBase.eval, which returns theMatrixOprepresentation, if no argument is passed. -
Adds
max_iterationsto theVQEAdaptclass 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_objectiveargument of the amplitude estimation algorithms has been renamed toobjective_qubits. -
TransformationType
-
QubitMappingType
-
Deprecate the
CircuitFactoryand derived types. TheCircuitFactoryhas been introduced as temporary class when theQuantumCircuitmissed 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.QuadraticProgramToIsingandqiskit.optimization.converters.IsingToQuadraticProgramhave been deprecated and will be removed in a future release. Instead theqiskit.optimization.QuadraticProgrammethodsto_ising()andfrom_ising()should be used instead. -
Deprecate the
WeightedSumOperatorwhich has been ported to the circuit library asWeightedAdderinqiskit.circuit.library. -
Core Hamiltonianclass is deprecated in favor of theFermionicTransformationChemistry Operatorclass is deprecated in favor of thetranformationsminimum_eigen_solvers/vqe_adaptis also deprecated and moved as an implementation of the ground_state_solver interfaceapplications/molecular_ground_state_energyis deprecated in favor ofground_state_solver -
Optimizer.SupportLevelnested enum is replaced byOptimizerSupportLevelandOptimizer.SupportLevelwas removed. Use, for example,OptimizerSupportLevel.requiredinstead ofOptimizer.SupportLevel.required. -
Deprecate the
UnivariateVariationalDistributionandMultivariateVariationalDistributionas input to theQuantumGenerator. Instead, plainQuantumCircuitobjects 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_iterin favor ofmaxiter. SPSA optimizer class deprecated__init__parametermax_trialsin favor ofmaxiter. optimize_svm function deprecatedmax_itersparameter in favor ofmaxiter. ADMMParameters class deprecated__init__parametermax_iterin 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_measurementproperty 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-community/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,
websockets7.0 was used for Python 3.6. With this release,websockets8.0 or above is required for all Python versions. The package requirements have been updated to reflect this.