Commit Graph

1312 Commits

Author SHA1 Message Date
Jake Lishman 2629079167
Fix `QuantumCircuit.compose` on unusual types and registers (#9206)
* Fix `QuantumCircuit.compose` on unusual types and registers

`QuantumCircuit.compose` previously had its own handling for converting
bit specifiers into bit instances, meaning its functionality was often
surprisingly less permissive than `append`, or just incorrect.  This
swaps the method to use the standard conversion utilities.

The logic for handling mapping conditional registers was previously the
old logic in `DAGCircuit`, which was called without respect to
re-ordering of the clbits during the composition.  The existing test case
surrounding this that is modified by this commit made an incorrect
assertion; in general, the condition was not the same after the
composition.  In this particular test case it was ok because both bits
were being tested for the same value, but had the condition value been
0b01 or 0b10 it would have been incorrect.

This commit updates the register-mapping logic to respect the reordering
of clbits, and to create a new aliasing register to ensure the condition
is represented exactly, if this is required.  This fixes a category of
bug where too-small registers could incorrectly be mapped to larger
registers.  This was not a valid transformation, because it created
assertions about bits that were previously not involved in the
condition's comparison.

* Remove now-outdated DAG compose test

This test was actually attempting to catch invalid state of
`QuantumCircuit.compose`, but this series of commits changes the
underlying function so that this test no longer needs to raise; there is
valid alternative behaviour.

* Fix lint

* Add comment explaining list copy

* Update test/python/circuit/test_compose.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-11 16:55:11 +00:00
Kevin J. Sung 7ed5de3eb5
support gate powering with ** (#9030)
* support gate powering with **

* separate test

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-11 14:49:19 +00:00
Kevin J. Sung 804665b4e7
Add option to allow passing unknown parameters to ParameterExpression.bind (#9304)
* add allow_unknown_parameters argument to ParameterExprression.bind

* format docs

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* improve docstring

* also add the argument to subs

* update Parameter.subs

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-11 13:34:26 +00:00
Jake Lishman 7fc7ab80f7
Speed up `Clifford.compose` (#7483)
* Speed up Clifford.compose

This is a fairly "dumb" optimisation; the algorithm remains exactly the
same, but the loops are refactored to do everything meaningful within
Numpy vectorised operations.  This has a slightly larger memory
footprint, than the previous versions in order to vectorise most
efficiently, but it is the same time complexity.

In practice, however, the speed-ups are very large.  On my machine, the
timings went (for Cliffords of `n` qubits and made from 10 gates each):

     n     new      old
      1   0.025     0.057
      3   0.146     0.162
     10   0.366     1.30
     30   1.11     13.5
    100   8.51    337

where all timings are in ms.  The scaling should not (in theory) be
different, but in practice, the faster Numpy vectorisation means larger
matrices get bigger speedups.

This transforms the 1-qubit case into a lookup table, populated on the
first call to `Clifford.compose` with 1-qubit operators.  There are 576
possible combinations of 1-qubit Clifford operators, which is small
enough to simply look up.  Having the special case is an optimisation
for randomised benchmarking scripts.  (In those cases, doing the lookup
manually can save another factor of 2x, because half the time spend in
this function is just copying the mutable values from the lookup table.)

This also adds a `copy` argument to the constructor of `Clifford` to
avoid copying the stabilizer table when it is not necessary.

* Remove duplicated lookup table

* Use unified tableau in hash

Co-authored-by: Ian Hincks <ian.hincks@ibm.com>

Co-authored-by: Ian Hincks <ian.hincks@ibm.com>
Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-11 10:48:44 +00:00
Shelly Garion ac3a021783
Synthesis of a Clifford circuit into layers (#9220)
* add more utils to linear_matrix_utils

* add clifford_decompose_layers

* add a test for clifford_decompose_layers

* add clifford_decompose_layers to init

* style

* remove copy when not needed

* add documentation

* replace assert by raise QiskitError

* change the order of the layers in the decomposed clifford

* update _gauss_elimination and _compute_rank

* update LayeredCircuit class

* add release notes

* enhance documentation

* few changes following review

* minor change

* remove references

* remove circuit image

* update API of synth_clifford_layers following review

* update test file name

* remove LayeredCircuit class by the review

* enhance the release notes

* add a test for the layered structure

* add a code example to the docs

* update docs

* update docs

* update docs

* add docstrings to the internal functions

* add more detais in the docs

* add circuit image to the notes

* update following review

Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>
2023-01-11 08:32:04 +00:00
Kevin J. Sung 67a89375e7
add dtype parameter to PauliSumOp.from_list (#8896)
* add dtype parameter to PauliSumOp.to_list

* add release note

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-10 16:02:20 +00:00
Kevin J. Sung d3243e9e1d
Add efficient gate power methods (#9318)
* add efficient gate power methods

* fix imports

* override some more methods

* use scipy.linalg.fractional_matrix_power

* use assertIsInstance and add isinstance check

* lint

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-10 10:41:48 +00:00
Will Shanks 0344a1c94b
Update `qiskit.utils.wrap_method` for Python 3.11 (#9310)
* Revert "[Test] Pin maximum python version in CI to <3.11.1 (#9296)"

This reverts commit 07e0a2fc79.

* Do not treat __init_subclass__ as a special type method

* Release note

* Apply suggestions from code review

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Use inspect.getattr_static to bypass descriptor call

* Update release note

* Update wrap_method test

* Adjust wording on release note

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-10 00:24:07 +00:00
Julien Gacon 244400ad19
Fix ``ComposedOp.to_matrix`` (#9316)
* Fix ComposedOp.to_matrix

* lint

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-09 22:56:33 +00:00
Matthew Treinish f0f8638af1
Remove deprecated MSBasisDecomposer transpiler pass (#9342)
This commit remove the deprecated MSBasisDecomposer transpiler pass. It
was originally added as the first initial support in Qiskit for
targeting ion trap backends and simply translated IBM's basis at the
time (U3 and CX) to an Rx, Ry, and RXXgate basis. Since then the basis
translator has completely supersceded this pass and nothing should be
using it anymore (independent of the deprecation).

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-09 15:28:33 +00:00
Declan Millar 9b58d415a2
Fix `NumPyEigensolver` with `SparsePauliOp` (#9101)
* Fix NumPyEigensolver for SparsePauliOp

* Use to_matrix instead for non-Operator BaseOperator children.
* Make NumPyEigensolver stateless w.r.t. results.
* Build operators as SparsePauliOps rather than PauliSumOps.

* Test NumPyMinimumEigensolver with different ops

Test NumPyMinimumEigensolver with:

* SparsePauliOp
* Operator
* PauliSumOp

* add releasenote

* Use sparse matrix computation for non-Operator

* Use sparse matmul for non-Operator

* improve structure

* try dense matrix for all BaseOperators or raise ex

* remove unused import

* test Operator.to_matrix()

* use instance to access sparse

* raise error for invalid num_qubits. pauliop/scalarop tests

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-09 14:17:52 +00:00
Julien Gacon 27da80d03f
Translate parameterized gates only in gradient calculations (#9067)
* translate parameterized gates only

* TranslateParameterized to proper pass

* update reno w/ new trafo pass

* Only add cregs if required

* rm unused import

* directly construct DAG

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* target support

* qubit-wise support of unrolling

* globally check for supported gates in target

that's because this pass is run before qubit mapping

* lint!

* updates after merge from main

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-06 22:13:56 +00:00
Will Shanks 86634bc40d
Add GaussianSquareDrag symbolic pulse shape (#9329)
* Add GaussianSquareDrag symbolic pulse shape

This pulse shape is similar to the GaussianSquare pulse with Drag
components in the rise and fall of the pulse.

* Clarify description of pulse

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-06 20:52:31 +00:00
Manoel Marques 35ab9cd752
Change algorithms status from pending deprecate to deprecate (#9345)
* Change algorithms from pending deprecate to deprecate

* fix test cases
2023-01-06 17:29:35 +00:00
Matthew Treinish 95a97ec53c
Stop using jupyter-sphinx extension in docs builds (#9346)
* Stop using jupyter-sphinx extension in docs builds

The use of the jupyter-sphinx plugin has been increasingly unreliable
over time. While convinient to use jupyter to print the code and
rendered output in practice this extension is exceedingly fragile. The
nature of how the plugin launches jupyter kernels and executes code
causes it to be prone to failure and weird issues. A race condition in
this machinery is causing a high non-deterministic failure rate in CI
right now preventing us from reliably building documentation. This
commit removes the use of the jupyter-sphinx extension from the
documentation. For the most part a drop-in replacement is the ``plot``
directive from matplotlib that enables executing code and visualizing
the result as part of the documentation build. But it does this more
simply through ``exec()`` which will be much more reliable. In many of
the cases jupyter-execute wasn't even needed because no output was shown
in those cases a simple code-block is used instead.

For release notes, new release notes are updated to use plot where
necessary but for historical release notes all jupyter-execute
directives are converted to code-blocks. This was done for sanity to
avoid having to manually update hundreds of release notes over the past
3 years.

This also enables us to enable parallel builds as jupyter-sphinx was the
extension which was unreliable in a parallel context. Doing this can
greatly speed up documentation builds (although the impact in CI will be
limited as we only have 2 vCPUs in the CI workers).

* Fix tests and lint

* Revert accidental change to tox.ini

* Fix capitalization of GHZ circuit

* Cleanup circuit library visualization function
2023-01-06 16:25:55 +00:00
Naoki Kanazawa e87324b02d
Fix PulseQobj converter name collision (#8839)
* Update pulse qobj converter. Reimplemented with visitor pattern.

* Add release note.

* Review comments
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Use method dispatch

* give descriptive method name
2023-01-06 12:52:57 +00:00
nick bronn 4b860332a6
Feature/trivial gate inversions (#9262)
* added line to pass through trivially symmetric 2Q rotations

* modified handling of symmetric rxx, ryy, rzz gates to more closely follow rzx, where the qargs are switched in the process. additionally added unit tests.

* removed commented lines from previous commit

* added release notes :)

* Update releasenotes/notes/fix-trivial-gate-inversions-1e39293d59bc6027.yaml

Yes, better to have links to the actual gates we're discussing!

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* extend tests

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2022-12-23 12:27:21 +00:00
Anthony-Gandon 049451d271
Refactor z2symmetries (#9227)
* first step

* first step and new files

* pass all tests

* Add release note and fix mypy

* First batch of corrections

* Second batch of Fixes: subtests, docstring, qiskiterror

* Fix release note

* First working attempt to factor find_Z2_symmetries

* Moved _sparse_pauli_op_is_zero to Z2symmetries

* rename find_Z2_symmetries to find_z2_symmetries

* Fix docstrings and refactor _test_symmetry_at_row_col method

* rm logging and fix type hints

* add return types

* fix lint

Co-authored-by: ikkoham <ikkoham@users.noreply.github.com>
2022-12-21 08:35:05 +00:00
Marc Sanz Drudis d932d88c81
Numerical Integration methods for real and imaginary time evolution. (#8399)
* All Changes so far

* Revert "All Changes so far"

This reverts commit 871f29ef54.

* Quantum Time Evolution

* operators and frob norm

* fro norm

* Changes

* changes

* Added history

* Removed files and fixed lint

* Changed name

* fixed accuracy associated to bicg

* Changed imaginary

* Fixed output for observables

* version

* changes

* Comments Part 1

* make black

* Changed output observalbes

* Changed to taylor expansion

* black

* Documentation

* black

* Some comments

* redesign

* changes

* restore evolvers

* unittest redoing path

* make black

* Fixed docs?

* Fixed issue with scipy1.7.3

* Delete 1.8

* Review

* Deleted opflow

* times documentation T_ev_result

* Added example to reno

* Julien review

* Update releasenotes/notes/scipy-evolvers-ca92bcb90e90b035.yaml

* Update releasenotes/notes/scipy-evolvers-ca92bcb90e90b035.yaml

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* observable in reno

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-20 20:12:36 +00:00
ElePT 1caf0306e7
Fix primitives metadata (#9285)
* Fix bug metadata

Co-authored-by: Julian Schuhmacher <jsc@zurich.ibm.com>

* Add reno

* Re-trigger CI

* Fix typo

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>

Co-authored-by: Julian Schuhmacher <jsc@zurich.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
2022-12-20 18:58:55 +00:00
Pedro Rivero c4c79ff600
Remove deprecated `measure` and `reset` circuit operations (#9278)
* Remove measure

* Remove reset

* Add reno

* Update reno

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-13 23:41:07 +00:00
a-matsuo b2c90395df
Refactor gradients for extensibility (#9084)
* wip skelton

* updated base_estimator_gradient and param shift

* updated

* updated preprocess

* move preprocess and postprocess

* update lin comb gradient

* updated estimator gradients

* updated sampler gradients

* update unittests and add reno

* fix lint

* made sampler result sparser

* fix lint

* updated reno

* fix reno

* combine all circuits into a single job

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: Max Rossmannek <oss@zurich.ibm.com>
Co-authored-by: Julien Gacon <jul@zurich.ibm.com>

* fix

* remove commented codes

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: Max Rossmannek <oss@zurich.ibm.com>
Co-authored-by: Julien Gacon <jul@zurich.ibm.com>
2022-12-13 13:31:53 +01:00
LNoorl 9c1c18cea4
Add the Solovay-Kitaev algorithm to the transpiler passes (#5657)
* add sk pass

* add utils

* add sk skeleton

* add example test file

* Add implementations initial version

* make the test run

* fix lint

* fix phase, add test

* fix the phase calculation

* add accuracy test

* cleanup of unused methods, append more efficient

* Add unittests for Solovay Kitaev Utils

* Add unitttests for commutator_decompose

* Remove unittests for non-public functions

* Fix pylint issues

* refactor simplify

* fix the test imports

* improve and add docstrings

* fix lint in testfile

* fix lint in utils

* fix lint in sk

* Add unittests

* fix phase, lint and allow basis gates as strings

* rm print

* fix adjoint and dot

* Fix unittests and add docstring to them

* move to circuit to GateSequence

* Fix assertion

* allow caching the basic approxs

* Fix bug in append from GateSequence

* Remove unnecesssary code

* Fix bug in test setup

* Add unittests for multiqubit QFT-circuit

* Add unittests for QFT with more qubits

* make compatible with current tests

* Remove unnecessary testcases

* Remove unnecessary unittests

* Fix bug in unittests

* Add release notes

* import scipy; scipy.optimize.fsolve() does not work

scipy.optimize has to be imported, since it is not imported when scipy is imported

* numpy

* Update qiskit/transpiler/passes/synthesis/solovay_kitaev_utils.py

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* document ValueError

* rm unused methods, add GateSequence tests

* fix lint

* try fixing lint and docs

* cleanup

* improve readability of math
* move commutator_decompose into utils
* rm tests that are never run
* rm trailing todos and commented code

* add default dataset, cleanup tests

* rm unused imports

* replace diamond norm by trace distance

* rm unused imports

* fix deprecated use of DAGNode.type

* black

* really black!

* fail nicely

* test

* attempt to fix default approx path

* Move decompositions into py file dict

* speed up the basic approx generation

* add candidate checking by string

further reduces the runtime by a factor of about 1.8!

* use a tree for basic approx generation

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>

* fix tests

* more speedups!

* use kdtree!

* refactor: generation as sep. function

* remove this masssssive file!

* start plugin work

* first attempt at synthesis plugin

* plugin itself works

-- but not when called via transpile or the UnitarySynthesis

* unitary synth works!

* use class-level method for SolovayKitaev

* docstrings

* add tests which cover still missing feature

* rename to SKSynth and better reno

* re-organize files

- algorithm to qiskit.synthesis
- plugin to qiskit.transpiler.passes.synthesis

* cover sklearn-free case

* missing future import

* move sk pass to transpiler subdirectory

* reno & try fixing slow optional module-level imports

* attempt 2 to fix sklearn import

* comments from Matthew's review

* directly construct dag

* (previous commit incomplete: missed this here)

* add SK to plugin toctree

* try fixing sphinx

* Apply Jake's comments

Removed the SK plugin from the plugin.py docs for now

* Fix doc example

* Update docs

* Fix tests

* Fix docs error

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2022-12-09 22:04:59 +00:00
Max Rossmannek 022aff617d
Various improvements to AdaptVQE (#9215)
* Various improvements to AdaptVQE

* A little more detail for the reno

* retrigger CI

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-08 15:16:06 +00:00
Matthew Treinish 7243c71ea1
Oxidize SabreLayout pass (#9116)
* Oxidize SabreLayout pass

This commit modifies the SabreLayout pass when run without the
routing_pass argument to run primarily in Rust. This builds on top of
the rust version of SabreSwap previously added in #7977, #8388,
and #8572. Internally, when the routing_pass argument is not set
SabreLayout will perform the full sabre algorithm both layout selection
and final swap mapping in rust and return the selected initial layout,
the final layout, the toplogical sorting used to traverse the circuit,
and a SwapMap for any swaps inserted. This is then used to build the
output circuit in place of running separate layout and routing passes.
The preset pass managers are updated to handle the new combined layout
and routing mode of operation for SabreLayout. The routing stage to the
preset pass managers remains intact, it will just operate as if a
perfect layout was selected and skip SabreSwap because the circuit is
already matching the connectivity constraints.

Besides just operating more quickly because the heavy lifting of the
algorithm operates more efficiently in a compiled language, doing this
in rust also lets change our parallelization model for running multiple
seed in Sabre. Just as in #8572 we added support for SabreSwap to run
multiple parallel trials with different seeds this commit adds a
layout_trials argument to SabreLayout to try multiple seeds in parallel.
When this is used it parallelizes at the outer layer for each
layout/routing combination and the total minimal swap count seed is used.
So for example if you set swap_trials=5 and layout_trails=5 that will run
5 tasks in the threadpool with 5 different seeds for the outer layout run.
Inside that every time sabre swap is run (which will be multiple times
as part of layout plus the final routing run) it tries 5 different seeds
for each execution serially inside that parallel task. This should
hopefully further improve the quality of the transpiler output and better
match expectations for users who were previously calling transpile()
multiple times to emulate this behavior.

Implements #9090

* Use deepcopy for coupling map copy

Previously this PR was using copy() to copy the coupling map before we
mutated it to be symmetric (a requirement for the sabre algorithm).
However, this modification of the object was leaking out causing test
failures. This commit switches it to a deepcopy to ensure there are no
shared references (and a comment added to explain it's needed).

* Fix failing unitary synthesis tests

This PR branch modifies the default behavior of the SabreLayout pass so
it is now a transformation pass that computes a layout, applies it, and
then performs routing. This means when using sabre layout in a custom
pass manager we no longer need to embed a layout after computing the
layout. The failing unitary synthesis tests were using a custom pass
manager and trying to apply the layout again after SabreLayout already
did. This commit just removes this now unecessary steps from the test
code.

* Add release note

* Run BarrierBeforeMeasurement before new SabreLayout

Now that the routing stage is integrated into the SabreLayout pass we
should be running the BarrierBeforeMeasurement pass prior to layout in
the preset pass managers instead of before routing. The goal of the pass
is to prevent the routing algorithms for accidentally reusing a qubit
after a final measurement which would be invalid by inserting a barrier
before the measurements to ensure all qubits are swap mapped prior to
adding the measurements during routing. While this might not strictly be
necessary (it didn't affect any test output) it feels like best practice
to ensure we're doing this prior to potentially routing to prevent
issues.

* Improve docstrings

* Set a fixed number of layout trials in preset pass managers

For reproducible results with a fixed seed this commit sets a fixed
number of layout_trials for the SabreLayout pass in the preset pass
managers. If we did not set a fixed value than the output of the
transpiler with a fixed seed will vary based on the number of
physical cores that is running the compilation. To start
optimization levels 0 and 1 use 5, level 2 uses 10, and level
3 uses 20 which matches the swap_trials argument we used. This is just a
starting point, we can adjust these values later if needed.

* Update tests for layout changes

This commit updates the tests which are checking exact layouts with a
fixed seed when running SabreLayout. The changes to SabreLayout breaks
exact seed reproducibility from the earlier version of the pass. So we
need to update these tests for their new layout assignment from the
improved pass. One exception is a test which was trying to assert that
transpile() preserves a swap if it's in the basis set. However, the new
layout and routing output from SabreLayout for that test was resulting
in all the swaps getting optimized away at optimization level 3
(resulting in 13 cx gates instead of ~4 cx gates and 5 swaps before,
which would be more efficient on real hardware). So the test was removed
and only run at lower optimziation levels.

* Set a fixed number of layout trials in SabreLayout tests

The dedicated tests for SabreLayout were not running a fixed number of
trials. This was causing a different layout to be returned in tests when
run across multiple systems as the number of trials defaults to the
number of physical CPUs. This commit fixes the trial count to the number
of cores on the local system where the layout was updated. This should
fix the non-determinism in the tests causing failures in CI and on
different local systems.

* Run SabreSwap in parallel if only a single layout trial

If there is only a single layout trial being run we don't have to worry
about trying to do too much work in parallel at once by parallelizing
the inner sabre swap execution. This commit updates the threading logic
to enable running the inner sabre swap trials in parallel if there is
only a single layout trial.

* Remove duplicated SabreDAG creation

* Correctly apply selected layout on dag nodes

This commit corrects a bug in the PR branch that was caused by applying
the selected initial layout in a trial to the swapped order node list.
This was causing unexpected results when applying the circuit because
the intent was to apply it only to the original input not the reversed
input.

* Remove unnecessary clone from serial layout trials

In the case we're evaluating the layout trials serially instead of in a
parallel iterator we don't need to clone the dag nodes list. This is
because nothing will be modifying it in parallel, so we don't need a
thread local copy. Each call to layout_trial() will keep the dag nodes
vector intact (see previous commit for fixing this) so it can just be
passed by reference if there are no parallel threads involved.

* Fix seed setup when no user seed specified

This commit fixes an issue prevent seed randomization when no seed is
specified. On subsequent uses of a pass SabreLayout would not randomize
the seed between runs because it was setting the seed to instance state.
This commit fixes this issue by relying on initializing the RNG from
entropy each time run() is called if no user specified seed is provided.

* Start from trivial layout for routing stage

This commit fixes the routing run to run from a trivial layout instead
of the initial layout. By the time we do final routing for a trial we've
already applied the selected initial layout to the SabreDAG. So the
correct layout to use for running final swap mapping is a trivial layout
where logical bit 0 is at physical bit 0. Using initial layout twice
means we end up mapping more than is needed resulting in incorrect
results.

* Revert "Correctly apply selected layout on dag nodes"

This change was incorrect, the output was already in the correct order
and this was causing the behavior it strived to fix. This commit reverts
the addition of the extra mem::swap() call to fix things.

This reverts commit d98ef6c4a1.

* Deduplicate NLayout trivial layout creation

This commit deduplicates the trivial layout generation for the NLayout
class. Previously there were a few places both in rust and python that
sabre layout was manually generating a trivial NLayout object. THis
commit adds a static method to the NLayout class that allows both Python
and Rust to easily create a new trivial NLayout object instead of
manually creating the object.

* Fix fixed layout tests after updates

Since more recent commits fixed a few bugs in the behavior of the
SabreLayout pass, the previously updated fixed layout tests were no
longer correct. This commit updates the tests which were now failing
because the layout changed again after fixing bugs in the new pass code.

* Try nesting parallelism in the sabres

Looking at profiles for running the new SabreLayout pass, as expected
the runtime of the rust SabreSwap routines is dominating. This is
because we've basically serialized the sabre swap routines and are
running multiple seed trials. As an experiment this commit sets the
inner SabreSwap routines to run in parallel too. Since the rayon
algorithm uses a work stealing algorithm this hopefully shouldn't cause
too much extra overhead, especially because the layout trials are quite
fast. This ideally means we're just scheduling each sabre swap trial in
a big parallel work queue and rayon does the rest of the magic to figure
out how to execute things. Initial testing is showing an improvement for
large circuits and a more modest improvement for more modest circuits.

* Add skip_routing argument to preserve custom user provided routing

This commit adds a new argument, skip_routing, to the SabreLayout
constructor. The intent of this new option is to enable mixing custom
routing_method user arguments with SabreLayout in it's new accelerated
mode of operation. In the earlier commits no matter what users specified
the preset pass manager construction would use sabreswap for routing as
it was run internally as part of layout. This meant doing something
like:

transpile(qc, backend, routing_method='stochastic')

would really run SabreSwap which is clearly not the user intent. To
provide the layout benefits with multiple seed trials this new argument
allows disabling the application of the routing found. This comes with a
runtime penalty because effectively we end up running routing twice and
only using one of the results. But for custom user provided methods or
plugins this seems like a reasonable tradeoff.

* Fix typo in docstring

* Update random seed usage in rust code

In #9132 we updated the random seed parameters in the rust code for
sabre swap to make the seed optional and default to initializing from
entropy if it's not specified. This commit updates the usage to account
for this change on main.

* s/retworkx/rustworkx/g

* Add alternate constructor for NLayout from a logic_to_phys vec

This commit adds a new constructor method to the NLayout class that
builds an NLayout object from just a logic_to_phys Vec. This constructor
can be accessed from either rust or python (although it's not as
efficient from Python). This is used to simplify some of the SabreLayout
rust code that was doing this inline manually.

* Move layout embedding into a method

This commit moves the code the optimized SabreLayout pass was using to
embed the found layout from the Rust code into a method. This will make
it easier to refactor later if a more efficient pass manager path is
added.

* Simplify pass logic and update comments

This commit removes an unnecessary else branch in the SabreLayout.run()
code to make it slightly easier to read. At the same time some comments
are updated to better explain the logic of the code.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-08 12:56:39 +00:00
Takashi Imamichi 45db5ec49f
Fix `LinCombSamplerGradient` to leverage `AerSampler` (#9258)
* fix LinCombSamplerGradient

* fix lib_comb circuit

* add reno

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-08 11:44:15 +00:00
Jake Lishman 840f44a574
Deprecate old path to QPY (#9225)
* Deprecate old path to QPY

This includes a try/except for the old name in the backwards
compatibility tests because we still need that test file to succeed
against old versions of Terra to generate the old files.

* Fix lint

* Do not warn on dunder access

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-08 10:36:29 +00:00
ElePT f339f7185e
Fix `betas` calculation on `VQD` and async. cost evaluation (#9245)
* Fix betas

* Add async

* Fix seed test

* Fix lint

* Add reno

* Add enumerate

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Apply suggestions Julien

* Fix lint

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-06 19:51:03 +00:00
Takashi Imamichi cc28f82644
Fix a transpile issue of BackendSampler (#9236)
* fix an issue of transpile of BackendSampler

* optimize

* add reno

* updated test

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-06 11:29:34 +00:00
Takashi Imamichi 0df0d29fc4
Performance improvement of `_DiagonalEstimator` (#9229)
* performance improvement of _DiagonalEstimator

* optimize

Co-authored-by: Jake Lishman <jake@binhbar.com>

* add reno

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-05 11:05:28 +00:00
Julien Gacon 0fe47d201f
Fix the ``aggregation`` argument of ``SamplingVQE`` (#9221)
* Fix the ``aggregation`` argument of ``SamplingVQE``

The aggregation was not passed to the DiagonalEstimator and had no effect. Also fixed  a bug in the CVaR aggregation function, which overshot the expected value and improved the docs.

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update qiskit/algorithms/minimum_eigensolvers/diagonal_estimator.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-05 09:11:20 +00:00
Pedro Rivero b08c6d6d89
Fully normalize observables in `BaseEstimator.run()` method (#9065)
* Fully normalize observables in BaseEstimator run method

* Fix type annotations

* Add str type to init_observable

* Simplify _validate_observables logic

* Add reference to Pauli string representations to docstring

* Fix sphinx domain in docstring

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-05 06:43:03 +00:00
Matthew Treinish cace20b513
Add DAGCircuit output option to OneQubitEulerDecomposer (#9188)
* Add DAGCircuit output option to OneQubitEulerDecomposer

This commit adds a new option to the euler one qubit decomposer class,
use_dag, which when set to True will return a DAGCircuit object for the
decomposed matrix instead of a QuantumCircuit object. This is useful for
transpiler passes that call the decomposer so that they don't have to
convert from a circuit to a dag. The passes that use the decomposer are
also updated to use this new option.

This was originally attempted before in #5926 but was abandoned because
at the time there was no real performance improvement from doing this.
However, since then this class has changed quite a bit, and after #9185
the overhead of conversion between QuantumCircuit and DAGCircuit is a
more critical component of the runtime performance of the 1 qubit
optimization pass. By operating natively in DAGCircuit from the
decomposer we're able to remove this overhead and directly substitute
the output of the decomposer in the pass.

* Use a dataclass for internal gate list and phase tracking

This commit updates the internal psx circuit generator function to pass
a dataclass with a field for the gates and phase instead of using 2
lists. This provides a cleaner interface for using a mutable reference
between the different functions used to add gates to the circuit.

* Directly combine op node lists in optimize_1q_commutation
2022-12-02 22:25:55 +00:00
Jake Lishman c5aa4ce400
Correct deprecation of old pulse visualization (#9146)
* Correct deprecation of old pulse visualization

Several of the components of the old pulse visualization package were
not correctly propagating their warnings up to user space, due to the
`stacklevel` setting blaming internal library code, or the warnings
being absent.  This commit corrects that oversight, and prepares for the
move of `pulse_v2` to simply `pulse` in a later version.

* Correct order of deprecation

* Avoid cyclic import lint failures

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-01 23:30:50 +00:00
Daniel Puzzuoli 8412ce2f41
Fix ordering of dims in QuantumState.probabilities_dict (#9214)
* fixing handling of ordering of qargs argument in QuantumState.probabilities_dict

* updating reno comment

* Update releasenotes/notes/probabilities_dict_bug_fix-aac3b3d3853828dc.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-01 22:31:33 +00:00
Matthew Treinish fd85047d3d
Enable simplifying 1q runs and 2q blocks in transpile() without target (#9222)
* Enable simplifying 1q runs and 2q blocks in transpile() without target

This commit fixes an issue when transpile() was called with optimization
enabled (optimization levels 1, 2, and 3) and no target (or basis gates)
specified then 1q run or 2q block optimization was run. This would result
in long series of gates that could be simplified being left in the output
circuit. To address this, for 1q optimization the
Optimize1qGatesDecomposition pass (which is run at all 3 optimization
levels) is updated so that if no target is specified we just try all
decomposers as the default heuristic for the best output is the
shortest sequence length (in the absense of error rates from the target)
and if any output gate is valid that will either remove the 1q sequence
if it's an identity sequence, or likely be a single gate. As no basis is
specified this behavior is fine since the calculations are quick and
any output basis will match the constraints the user provided the
transpiler.

For optimization level 3 with it's 2q blcok optimization with the
UnitarySynthesis pass it is a bit more involved though. The cost of
doing the unitary synthesis is higher, the number of possible
decompositions is larger, and we don't have a good heuristic measure
of which would perform best without a target specified and it's not
feasible to just try all supported basis by the synthesis module.
This means for a non-identity 2 qubit block the output will be a
UnitaryGate (which without a target specified is a valid output).
However, to address the case when an identity block is present in
the circuit this can be removed with very little overhead. To accomplish
this the ConsolidateBlocks pass is updated to check if an identified
2 qubit block is equal the identity matrix and if so will remove that
block from the circuit.

Fixes #9217

* Fix docs build

* Fix handling of 1q decomposer logic with no basis gates

This commit fixes an oversight in the previous commit for the 1q
decomposer pass when no basis gates are specified. Previously we were
setting the basis list to be the set of all the gates in the supported
euler basis for the decomposer. This had the unintended side effect of
breaking the heuristic for the decomposer as it would treat any 1q gate
outside of the supported euler basis as needing to be translated. This
was not the desired behavior as any gate is valid. This fixes the logic
to just treat no basis explicitly as everything being valid output and
weight the heuristic error only.

* Remove debug prints

* Remove unnecessary conditional 1q identity matrix creation

* Split out release notes for 1q and 2q cases

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-01 19:39:22 +00:00
TsafrirA 4342881e19
Converting the pulse library from complex amp to amp+angle (#9002)
* Converting Gaussian SymbolicPulse from complex amp to amp,angle.

* removed unnecessary import.

* Completed the changes.

* Bug fix and test updates.

* removed commented line.

* black correction.

* Tests correction.

* Bump QPY version, and adjust QPY loader.

* Release Notes.

* Update qiskit/qobj/converters/pulse_instruction.py

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>

* Update releasenotes/notes/Symbolic-Pulses-conversion-to-amp-angle-0c6bcf742eac8945.yaml

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>

* Some more corrections.

* QPY load adjustment.

* Removed debug print

* Always add "angle" to envelope

* black

* Update qiskit/qpy/__init__.py

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>

* resolve conflict

* Remove outdated test.

* Lint

* Release notes style

* Removed QPY version bump in favor of using qiskit terra version as an indicator.

* bug fix

* bug fix

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-30 16:27:52 +00:00
Shelly Garion 0785ab3131
Transfer clifford and cnot-dihedral synthesis functions from quantum_info to synthesis (#9141)
* transfer clifford synthesis functions from quantum_info to synthesis

* add init file

* transfer cnotdihedral synthesis from quantum_info to synthesis

* rename clifford synth functions. add docs

* add clifford synthesis methods to docs

* add documentation for cnotdihedral synth methods

* add decompose_cnotdihedral to quantum_info docs

* deprecate decompose_clifford and decompose_cnotdihedral - move to qsikit.synthesis

* style

* add clifford and cnotdihedral decompose full to synthesis

* enhance tests

* update high_level_synthesis transpiler pass

* add release notes

* fix docs in synthesis plugin

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-30 14:57:38 +00:00
Shelly Garion 61e0bafef9
Adding linear synthesis algorithm for LNN (#9098)
* update init file

* add a test for kms synthesis for lnn

* add a synthesis algorithm based on kms for lnn in depth 5n.

Co-authored-by: Ben Zindorf <benzindorf@gmail.com>

* minor fixes in linear_depth_lnn

* fix import

* add release notes

* updates following review

* more updates following review

* add synth_cnot_depth_line_kms to docs

* updates following review comments

* fix init

* add Patel-Markov-Hayes to docs

* update docstring

* add Patel-Markov-Hayes to release notes

Co-authored-by: Ben Zindorf <benzindorf@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-29 17:32:01 +00:00
Pieter Eendebak 11eb8910a1
Fix shots argument of local_readout_mitigator (#9155)
* fix shots argument of local_readout_mitigator

* fix correlated_readout_mitigator as well

* add test

* docstring

* black

* lint

* add release notes

* Fix up release note

Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-11-24 23:49:15 +00:00
Jake Lishman c063c91df0
Remove deprecated functions from `ParameterView` (#9184)
* Remove deprecated functions from `ParameterView`

These were deprecated since Terra 0.17, when the type of the return
changed.

* Restore non-deprecated function

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-24 18:20:06 +00:00
Alexander Ivrii 0fddf79a22
Adding CollectAndCollapse transpiler pass (#8907)
* Collecting and refining blocks of nodes from DAGCircuit and DAGDependency

* Fix to visualize Cliffords

* Changing method descriptions to refer to Operation instead of Instruction

* Adding replace_block_with_op method to DAGDependency

* Changing dagdependency_to_circuit and dag_dependency_to_dag to iterate over the nodes in topological order

* Tests for collecting blocks

* Adding CollapseChains base transpiler pass

* Reimplementing CollectLinearFunctions using CollapseChains

* Expanding tests for CollectLinearFunctions

* Add CollectCliffords transpiler pass and tests

* Adding new passes to __init__

* Adding release notes

* minor renaming

* pylint fix

* pylint fixes

* Fixing template matching test. By changing dagdependency_to_dag to use topological order, the constructed dag arranges gates in a slightly different order

* minor releasenotes fix

* docs fixes

* Generalizing CollapseChains to a very general collection and consolidation pass

* more reno polishing

* pylint

* Renaming create_op_node to _create_op_node

* adding clarification message

* release notes fix

* adding test as per review comments

* adding one more collection test

* adding tests with measure and conditional gates

* removing debug print function

* renaming

* Following the review comments, moving the arguments split_block and min_block_size to be a part of collection function

* improving docstrings

* Fixing/extending tests for collecting blocks (to account for new options), allowing to run multiple collections with different filter functions

* docstring fixes

* docstring fixes

* apply renaming from code review

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-23 20:35:06 +00:00
Jake Lishman 35733a5c34
Infer `cregbundle` for all drawers (#9133)
* Infer `cregbundle` for all drawers

This swaps the default behaviour for the `cregbundle` to always bundle
if possible, but not to emit a warning if the bundles are expanded and
no concrete value was given for the parameter.  Previously, this sort of
logic was only done for the text drawer.

* Update tests for new default behaviour

Many tests use the internal `_text_circuit_drawer` function, which has
different defaults to the standard `circuit_drawer` function.  Since
this commit chain made this default the same all the way through the
tree, several tests changed their output, or needed the keyword
arguments updating.

* Fix missing warning test

* Revert unrelated expectedFailure changes

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-23 16:32:02 +00:00
Max Rossmannek 324c875eba
fix: QNSPSA with max_evals_grouped exceeding 1 (#9182)
Co-authored-by: Julien Gacon <gaconju@gmail.com>

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-23 12:38:19 +00:00
Naoki Kanazawa e5ea411837
Fully QPY compatible pulse builder for V2 and runtime backend (#8949)
* Eliminate use of Schedule in the builder context. Schedule is implicitly converted into ScheduleBlock with AreaBarrier instructions.

* Support AreaBarrier instruction in QPY

* Update RZX calibration builder to generate ScheduleBlock

* Add release note

* Support python3.7

* Fix hadamard schedule in the RZX builder. This should not use sequential context.

* Review comments

Co-authored-by: Daniel J. Egger <38065505+eggerdj@users.noreply.github.com>

* Unified append_block and append_subroutine

* Update instruction name AreaBarrier -> TimeBlockade

* Documentation updates

Co-authored-by: Daniel J. Egger <38065505+eggerdj@users.noreply.github.com>

* Remove old name

* lint fix

* add release note for bugfix

* review comments
- render class docs of the directive instructions
- update qpy format documentation
- add separate reno for time blockade

* more detailed upgrade notes

* add new unittests. rescale_cr_inst method is updated so that it becomes more robust to the rounding error.

Co-authored-by: Daniel J. Egger <38065505+eggerdj@users.noreply.github.com>
2022-11-23 09:28:07 +00:00
Matthew Treinish 83c84b0098
Improve performance of VF2 scoring and add support for scoring passes (#9026)
* Improve performance of VF2 scoring and add support for scoring passes

This commit makes 2 key changes to the vf2 layout pass. The first is it
migrates the scoring routine to rust. When running vf2 layout and vf2
post layout we're bottlenecked by the performance of the scoring of a
layout since in practice scoring a large circuit ends up taking more
time than the vf2_mapping() function. To address this the scoring
function is migrated to rust where the iteration will be much faster. To
enable this rust migration the average error map is made into a 2D numpy
array which can be efficiently be accessed by reference from rust. This
additionally also enables a convenient interface for future expansion of
the vf2 layout passes. The VF2LayoutPass and VF2PostLayout passes will
now both look for a "vf2_avg_error_map" entry in the property set which
contains a 2d array used for scoring. If present that array will be used
for scoring instead of the computing one from the target's error rates.
This will enable custom analysis passes to be run pre-layout to compute
or inject a custom scoring heuristic.

* Handle missing qubits from properties Payload

For BackendV1 based backends it's possible for the BackendProperties
object for that beackend to get out of sync with the number fo qubits
actually available in the system. In such cases looking up the noise
characteristics can potentially fail when building the error map because
the reported number of qubits is less than the qubits there are
properties for. This wasn't an issue in the previous error map data
structure because it was a dictionary and it would just add the error
rate for the extra qubits even though it wasn't valid. However, now that
we're using a numpy array with a fixed size this isn't the case anymore
and an error would be raised in these cases. To workaround this issue
this commit skips any qubits outside the allowed range in the
BackendProperties when building the error map to account for this
potential discrepency. The extra properties couldn't be used anyway
since they're not valid device qubits in such cases.

* Limit number of intermediate Layout objects created

This commit updates the vf2 layout scoring to work with a dictionary
object instead of a Layout object.  Previously we were creating a Layout
object on each mapping found and passing that to scoring. However, this
was unecessary overhead as the Layout object is slow to create and
interact with. Since we only need a Layout object if we're potentially
returning the layout as the best result we can avoid this extra
overhead.

* Move environment variable check outside loop

This commit removes the lookup for the QISKIT_IN_PARALLEL env variable
from the rust code for vf2 scoring. THis was adding unecessary overhead
to a frequently called function when it only needs to be computed once.
This commit moves the lookup to python outside the for loop and just
passes the evaluated boolean to the rust function instead.

* Fix rust lint

* Apply suggestions from code review

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Simplify duplicated rust iteration code

This commit deduplicates a bunch of the rust side code for scoring into
2 closures and replaces all the reduce() calls with product() to
accomplish the same thing.

* Update qiskit/transpiler/passes/layout/vf2_layout.py

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Use np.full() instead of np.empty() and np.fill()

* Pivot from 2d numpy array to a custom ErrorMap class

In order to support large (> 1000) qubit systems efficiently this commit
pivots away from using a 2d numpy array to represent the average error
rates for a target. For 1000q this error matrix would take 8 MB of
memory but for 10k qubit it would take 800 MB. Considering by their
nature these error matricies should be fairly sparse as connectivity in
typical QPUs is sparse. This was just wasted memory as we'll end up with
a lot of NaN values in the array. Instead this commit adds a new Rust
struct/Python class ErrorMap which just wraps a HashMap and maps a 2
element int array to a float. This way we only store entries where there
is defined connectivity and are more memory efficient.

* Fix lint

* Fix import path after rebase

* Update release notes

* Apply suggestions from code review

Co-authored-by: Kevin Hartman <kevin@hart.mn>

* Build empty ErrorMap in case of no target or coupling map

* Add helper function for layout creation in VF2Layout scoring loop

* Add test with custom ErrorMap analysis pass

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Kevin Hartman <kevin@hart.mn>
2022-11-18 23:47:59 +00:00
Matthew Treinish b9def99979
Switch from retworkx to rustworkx package (#9162)
* Switch from retworkx to rustworkx package

In the retworkx/rustworkx 0.12.0 release the package was renamed from
retworkx to rustworkx which was done at the request of the networkx
maintainers [1]. While the retworkx name continues to work for backwards
compatibility, it is best to move off of the legacy name and start using
the new name sooner rather than later. This commit updates all the
retworkx usage to the new rustworkx and updates our requirements list to
directly depend on rustworkx.

[1] https://qiskit.org/documentation/rustworkx/release_notes.html#prelude

* Fix release note path

* Update releasenotes/notes/rustworkx-not-retworkx-b7c4da600df58701.yaml

Co-authored-by: Jake Lishman <jake@binhbar.com>

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-18 20:44:53 +00:00
Lukas Burgholzer 80d12e079c
Increase Accuracy of OpenQASM 2.0 Dump (#8250)
* use tighter `eps` of `1e-12` in `qiskit.circuit.instruction.Instruction.qasm`

* change to `double` precision (`ndigits=16`) in `qiskit.circuit.instruction.Instruction.qasm`

* add tests

* refactor `pi_check` to use default float formatting when `ndigits=None`

* add release notes

* fix tests

* use parameter `eps` in check for zero in `pi_check`

* fix tests by changing default `eps` to `1e-9`

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-11-18 19:08:34 +00:00
Max Rossmannek e4ea0675cd
fix: overwrite AdaptVQE.supports_aux_operators (#9142)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-18 15:57:32 +00:00
Ali Javadi-Abhari 34ee9a9394
Update Optimize1qGatesDecomposition to be Target aware (#8917)
* make Optimize1qGatesDecomposition target aware

* choose decomopsition based on fidelity

* fix test that assumed cost of u3 vs. u1 to now rely on target

* always replace identity with empty

* black

* remove a bunch of unnecessary basis translations in tests

* tests for the target path

* add to preset passmanagers

* fixup Optimize1qGatesSimpleCommutation to work with new Optimize1qGatesDecomposition

* dont access duration and error unconditionally

* black

* more docs

* lint

* simplify test

* work around not being able to filter global gates by qubit

* review comments

* add a test for the case of no errors specified in target: pick shortest decomp.

* performance for qubit index lookup

* black

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-17 22:42:56 +00:00
Alexander Ivrii 02788a158a
Adding permutation synthesis algorithm for LNN (#9082)
* Adding permutation synthesis algorithm for LNN

* release notes

* Checking that the synthesized permutation adheres to the LNN connectivity and has depth guaranteed by the algorithm

* Adding tests for 15 qubits

Co-authored-by: Nir Gavrielov <nirgavrielov@gmail.com>

* fixing assert

* improving description message for _get_ordered_swap

* applying suggestions from code review

* minor

* attempt to fix docstring

* Another attempt to fix docsting

* another attempt to fix docstring

* temporarily simplifying docstring to see if this passes docs build

* adding blank line

* another attempt

* Restoring docstring

* removing extra line

* speeding up _get_ordered_swap based on review comments

Co-authored-by: Nir Gavrielov <nirgavrielov@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-17 19:38:32 +00:00
Ikko Hamamura 2bd4afacdc
Add gradient methods to FinDiffGradients (#9104)
* implement gradient methods

* fix docs

* arg order/refactor

* fix docs

* revert central difference

* Update qiskit/algorithms/gradients/finite_diff_estimator_gradient.py

* fix docs

* Update qiskit/algorithms/gradients/finite_diff_sampler_gradient.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-17 15:50:26 +00:00
Jake Lishman 30f45fe79a
Remove deprecated redirects from visualization (#9131)
These were deprecated in 0.21, since the lazy optional checkers in
`qiskit.utils.optionals` became available.

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-17 14:34:04 +00:00
Ikko Hamamura a4a6be00c4
Fix serialization of primitives (#9076)
* fix serialization of primitives

* Update releasenotes/notes/fix-serialization-primitives-c1e44a37cfe7a32a.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* rm tests

* Update releasenotes/notes/fix-serialization-primitives-c1e44a37cfe7a32a.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2022-11-17 12:51:05 +00:00
Ikko Hamamura 599b663e69
fix #9102 (#9103)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-17 03:25:24 +00:00
Jake Lishman da1a7e3093
Reinstate `pulse.Instruction.draw` (#9144)
This was erroneously broken by gh-8306 and not detected by lint because
of the existence of `qiskit.visualization.__getattr__`.  This reinstates
the functionality using the deprecated old instruction drawers.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-16 20:12:43 +00:00
Luciano Bello a1cdb70847
Removed NLocal inital_state that is not a QuantumCircuit (#9081)
* removed NLocal inital_state that is not a QuantumCircuit

* other instance of a check

* typehint

* lowering type in the lattice

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-16 18:22:59 +00:00
Matthew Treinish dfbc738be5
Fix random seed initialization between runs in SabreSwap (#9127)
* Fix random seed initialization between runs in SabreSwap

This commit fixes an issue in the case no random seed is provided by the
user when initializing an instance of SabreSwap. The pass was previously
potentially reusing the random seed between runs even if no seed was
specified. This was an artifact of storing the initial seed as an
instance variable. Instead this commit just relies on the the Rust RNG
to initialize from entropy if no seed is specified.

* Remove unused numpy import
2022-11-15 13:36:58 +00:00
Dariusz Lasecki 8bfb058b9d
Fixed sign bug in docs in LinCombEstimatorGradient. (#9113) 2022-11-11 21:31:29 +01:00
Jake Lishman c0ac5fbd21
Fix QPY handling of registers (#9095)
* Fix QPY handling of registers

QPY previously had rather complicated logic to handle deserialisation of
registers that was heavily couched in the old model of registers
"owning" the bits they contained.  This is no longer the data model of
the circuit, so the code was naturally complex to try and make it work.

Instead, in deserialisation now we just add the correct number of bit
instances to the circuit at the start, and then build up any required
registers by using the `indices` field.

It's not clear to me how an index ever could be negative here; it's not
clear how a register could be in the circuit but its bits aren't added,
so it feels like there might be the possibility of a bug I've missed.

* Remove unused import

* Add tests cases of empty registers

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-09 23:25:02 +00:00
Matthew Treinish b2d3dcf53e
Fix Backend primitive classes for BackendV1 with no max_experiments (#9069)
* Fix Backend primitive classes for BackendV1 with no max_experiments

The ``max_experiments`` field in the BackendConfiguration for a BackendV1
backend is not a required field. While in practice most real backends
set it, some simulators (including aer) do not. This causes a failure
when using the Backend primitive classes with these backends as we were
previously assuming the ``max_experiments`` attribute was always
present.

* Update test/python/primitives/test_backend_estimator.py

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-03 20:59:52 +00:00
Shelly Garion 94bccd55a5
Improve LinearFunction synthesis (#8568)
* move graysynth from transpiler.synthesis to synthesis.linear

* add linear utilities for binary matrices: inverse matrix, random matrix

* update random invertible binary matrix in random_cnotdihedral

* update random invertible binary matrix in test_linear_function

* fix deprecation warning in graysynth

* style

* update variable names

* add a function with 4 options to synthesize a CX circuit

* improve linear_utils code

* refactor transpiler/test_synthesis to synthesis/test_gray_synthesis

* split linear_utils into two files

* style

* add test/python/synthesis init file

* unify linear utils code

* add check_invertible_binary_matrix function

* update import in high_level_synthesis transpiler pass

* update transpose_cx_circ, add docstrings

* minor fix in calc_inverse_matrix

* add types in docstrings

* add tests for linear synthesis functions

* fix transpose_cx_circ function

* add docstrings in linear_matrix_utils

* update import
in test

* fix docs in linear matrix utils

* add a test for invertible matrices

* style changes

* add release notes

* fix random_invertible_binary_matrix

* update following review comments

* fix type hint

* fix import

* fix release notes

* renmae cnot_synth to PMH_cnot_synth

* add comments following review

* fix release notes following review

* add a test following review

* rename cnot_synth to PMH_cnot_synth

* rename to synth_cnot_count_full_pmh

* format tests

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-03 14:09:46 +00:00
Matthew Treinish 08969a6c2a
Remove deprecated networkx dag converter functions (#9035)
* Remove deprecated networkx dag converter functions

This commit removes the deprecated DAGCircuit and DAGDependency
networkx converter functions. These functions were deprecated
in #7927 as part of the 0.21.0 release. Since the minimum
deprecation window has elapsed we can now remove these functions and
the last usage of optional networkx usage in qiskit terra.

* Remove unused imports

* Move release note to the correct location

* Add networkx to tutorials job environment

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-11-03 12:56:22 +00:00
Jake Lishman 45f7836476
Avoid deepcopy in pulse parser (#9063)
This deepcopy is not strictly necessary; since we already own the nodes
we're modifying, we only need to shallow copy nodes that we want to
replace.  In practice, the deep copy seems to cause difficult-to-resolve
reference cycles within Jupyter that can get the parser.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-03 11:09:43 +00:00
Jake Lishman b0f3d5cbe8
Remove deprecated methods from QuantumCircuit (#8980)
* Remove deprecated methods from QuantumCircuit

This removes the old `c?u[1-3]` methods from `QuantumCircuit`, along
with the `combine` and `extend` methods.  The numbered-argument `UGate`
alternatives had been deprecated since Terra 0.16, and the simpler forms
of `compose` since 0.17.

The `U1Gate` class, and so on, are left in so the transpiler and
equivalence rules can still support legacy backends with these as basis
gates, but their privileged place as direct methods on `QuantumCircuit`
is removed.

* Fix lint failures

* Remove now-unused private method

* Correct release note

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-02 21:14:05 +00:00
Jake Lishman 61ca9ca6b2
Fix incorrect graph construction in VF2PostLayout (#9058)
The `add_nodes` call should be outside the loop; inside, it adds nodes
quadratically.  This commit also squashes a minor inefficiency in set
allocation.
2022-11-02 17:31:47 +00:00
Jake Lishman a2ea9288a2
Add implicit iteration to CouplingMap (#9051)
* Add implicit iteration to CouplingMap

This adds an `__iter__` method that passes through to iteration through
the underlying rustworkx `EdgeList` (after construction).  This commit
does not add the other methods needed to make `CouplingMap` into a
Python sequence, such as `__getitem__` and `__len__`, because
constructing the `EdgeList` has a nonzero cost (the rustworkx
implementation eagerly collects the edge indices into a `Vec` to iterate
over), and could lead to hidden performance pitfalls.  The edges also
have no particular order associated with them, so implementing
`Sequence` would be a misnomer.

As a side-effect, this makes it legal to pass a `CouplingMap` instance
to the `CouplingMap` constructor, but this is not a true copy
constructor (which in Python are perhaps better spelled as
`CouplingMap.copy()` so immutable objects can avoid the new-object
allocation cost without messing around with `__new__`), since fields
like `description` would not be copied.  This commit takes no position
on whether a true copy constructor is a good idea.

* Fix terrible manual sorting

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-02 14:30:49 +00:00
Lev Bishop fb16712ae4
Make TwoQubitWeylDecomposition pickle-able (#7333)
* Make TwoQubitWeylDecomposition pickle-able

Partial fix for #7312

* Remove docs xref

* Enforce minimum pickle protocol version 4

* Add release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2022-11-02 12:34:37 +00:00
Kevin Hartman d56ef8c49c
Use TOQM routing staged pass manager. (#9042)
* Update toqm requirements-dev version.

* Remove toqm special casing.

* Remove unused imports from preset pass managers.

* Add release note.

* Apply suggestions from code review

Co-authored-by: Jake Lishman <jake@binhbar.com>

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-01 20:16:43 +00:00
Julien Gacon e4a7c40716
Fix default batching in variational algorithms (#9038)
* Fix default batching in variational algorithms

* fix test

* reduce batching to only SPSA

* fix tests

* Apply suggestions from code review

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-01 18:39:46 +00:00
a-matsuo 671e81c674
QFI with the primitives (#8688)
* wip qfi

* wip qfi

* updated

* added tests

* updated

* updated

* updated

* lin comb qfi

* fix

* finilizing

* fix lint

* started working on block diag qfi

* updated utils

* fix

* fix options

* fix

* lint

* fix

* fix list

* remove estimator from base qfi

* fix

* make a directory for gradient tests

* added option to baseqfi + fied shots behavior

* fixed qfi's derivative type complex

* fix

* fix

* make parameter_values back to float

* updated

* fix lint

* updated

* updated

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-01 17:14:37 +00:00
Matthew Treinish f6a343b3fc
Fix handling of global ideal gates for target build_coupling_map() (#8977)
* Fix handling of global ideal gates for target build_coupling_map()

This commit fixes the handling of the `build_coupling_map()` method so
that it correctly handles edge cases around a mix of ideal globally
available gates and gates that have qubit/connectivity constraints.
Previously, the method would incorrectly treat the presence of a
globally defined ideal gate as meaning there were no connectivity
constraints, even if that global gate was only on 1 qubit. While if the
gate operates on two qubits this is correct behavior.

Fixes #8971

* Add test for single qarg non-ideal case
2022-10-31 17:29:30 +01:00
Matthew Treinish 77588ff3d3
Fix backend primitives on backends with job size limit (#8955)
* Fix backend primitives on backends with job size limit

This commit fixes an oversight in the initial implementation of the
BackendSampler and BackendEstimator class. When targeting real backends
most backends have job size limits that prevent sending an arbitrary
number of circuits in a single job (for example aqt provider backends
can only take a single circuit at once). In such cases the backend
primitive class ignored this constraint and would send as many circuits
as was passed to `run()` to the backend at once. This commit fixes this
by checking if the backend has a job size limit and chunking the
circuits into multiple jobs.

* Update releasenotes/notes/fix-max_circuits-backend-primitives-c70590bca557001f.yaml

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Add release note for monitor removal

* Update estimator tests to count mock backend.run() calls

* Unify run path between primitives

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-31 11:08:09 +00:00
Jake Lishman bb93592dd8
Fix zero-operand gates and instructions (#8272)
* Fix zero-operand gates and instructions

A few checks in different places didn't account for zero-operand gates
being possible.  In most uses, there never would be anything useful
here, but it can occasionally be useful to create a "global-phase"
instruction, especially if this is later going to have controls applied
to it.  This is well-formed within the Qiskit data model; spectator
qubits implicitly undergo the identity, so this corresponds to the
global phase being multiplied by the identity on _all_ qubits.

* Fix controlled-gate qubit-number documentation

* Add ScalarOp test

* Be stricter about allowed num_ctrl_qubits

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-29 09:27:23 +00:00
Matthew Treinish b6f8cab2f5
Deprecate Python 3.7 support (#8942)
This commit deprecates Python 3.7 support. During the deprecation window
we will continue to fully support Python 3.7 and test it in CI, but it will
emit a warning that we will be removing support for 3.7 in the future to
inform users to upgrade to Python 3.8 or newer. The removal will occur
during the qiskit-terra 0.25.0 release as it is the first release scheduled
to occur after the upstream Python EoL date in June 2023. [1]

[1] https://devguide.python.org/versions/

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 22:46:30 +00:00
Kevin J. Sung 8b58a8f41e
add QuantumCircuit.from_instructions (#9006)
* add QuantumCircuit.from_instructions

* simplify loop

* handle both cases in just one method

* delete stray import

* fix type annotation

* address comments

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 21:29:33 +00:00
Jake Lishman 351da447f7
Speed up `random_circuit` (#8983)
* Speed up `random_circuit`

There is no need to use the slower `append` (which adds a lot of
checking overhead for large circuits) since we fully control the
construction of the circuit.

This also overhauls all the randomisation components to produce all the
necessary randomness for a given layer in a single go.  This massively
reduces the Python-space and Numpy-dispatch overhead of the nested loop.

The changes to the randomisation in this new form mean that on average,
more gates will be generated per circuit, because the output will choose
1q gates more frequently than it chooses 2q, which in turn will be more
frequent than 3q, but each layer of the "depth" still has to involve
every qubit.  The change is because the likelihood of choosing a gate
with a given number of qubits is now proportional to how many different
gates of that number of qubits there are in the options.

For sample timings, the call `random_circuit(433, 1000, seed=1)` went
from 15.2s on my machine (macOS Python 3.10, Intel i7 @ 2.3 GHz) down to
2.3s, so a speed-up of about 6-7x.

* Add test of large-circuit condition generation

* Use all gates in the standard library

This deliberately does not use the `get_standard_gate_name_mapping`
function, in order to avoid changes to that function breaking RNG
compatibility in this unrelated function.

* Fix docstring

* Add comments on algorithm

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 20:20:06 +00:00
Jake Lishman b45afea036
Add missing equivalences for XX{Plus,Minus}YYGate (#9017)
* Add missing equivalences for XX{Plus,Minus}YYGate

These are just copied from the `_define` method on the classes.  The
equivalence-library tests are updated (since `subTest` doesn't isolate
correctly with `testtools`) to print out all the names of the tests
being run, so it's clear that the existing test now tests these
definitions.

* Use default parameters to beat the scoping weirdness

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 12:58:11 +00:00
Matthew Treinish 72ba2ee259
Fix transpile() with a Target containing an ideal Measure (#8995)
This commit fixes an oversight in the transpile() function when running
with a Target (either directly or via a backend) that contains a
Measurement operation that is ideal (either globally or locally) with no
properties defined. This was not handled correctly in the function used
to convert a Target to a BackendProperties payload for passes that are
not yet target aware and this would cause an exception to be raised.
This commit fixes this edge case and excludes readout properties from
the generated BackendProperties in this case.

Fixes #8969

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 05:28:20 +00:00
Julien Gacon aab18fcd69
Fix `VQD` for `k>2` (#8989)
* Fix vqd for k>2

Also ensure the optimal circuits from previous iterations are only constructed once and recognizable by the primitive caches.

* Remove empty parameter list

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-27 09:01:21 +00:00
Edwin Navarro de35b90ddb
Fix manifest entry for mpl styles (#9004)
* Fix manifest entry and reno

* Improve release note

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-26 22:51:28 +00:00
Ikko Hamamura be1e697613
fix #8992 (#8998) 2022-10-26 08:40:52 +00:00
Matthew Treinish 6580d96879
Fix VF2Layout and VF2PostLayout handling of instructions without error (#8978)
* Fix VF2Layout and VF2PostLayout handling of instructions without error

This commit fixes an issue in the VF2Layout and VF2PostLayout pass where
the passes would potentially error in cases when a target was specified
and there were instructions present without any error rates defined. In
such cases the instructions should be treated as ideal (having no error)
and the passes shouldn't fail. In cases where there are no error rates
in the target for VF2Layout the first perfect match should be used, and
for VF2PostLayout it should effectively be a no-op and not select a new
layout.

Fixes #8970

* Add missing comma to comment

* Exit early if score is 0

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-25 21:51:24 +00:00
Will Shanks 0ba7a438bd
Avoid skipping channels in pulse visualizer (#8974)
* Modify pulse visualizer test to fail due to missing channel

Reproduces #8981

* Avoid skipping channels in pulse visualizer

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-24 04:45:49 +00:00
Jake Lishman 6aad914189
Remove tweedledum as a core dependency (#8947)
* Remove tweedledum as a core dependency

Maintenance on tweedledum has stagnated in recent months, and is no
longer stable enough on our Tier-1 (and other) supported platforms,
especially as further Python versions are released.  This work was
heralded by gh-8738, which contains more context on the change.

* Add tweedledum pylint suppressions

I couldn't get `.pylintrc`'s `ignore{,d}-modules` options to work right
for this, so I just resorted to localised suppressions.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-20 18:17:04 +00:00
Matthew Treinish ef9259ded6
Fix parallel dispatch with target argument in transpile() (#8952)
* Fix parallel dispatch with target argument in transpile()

If a custom target was specified when calling the transpile() function
with more than one circuit the parallel dispatch of the shared custom
target would fail because the basis_gates created from the target was a
dict keys type. Pickle is unable to serialize a dict keys object
apparently and this would cause an exception to be raised. This commit
fixes this by casting the basis_gates from the target as a list so that
it can be serialized.

* Use unittest.mock.patch.dict to set parallel execution in tests

* Fix parallel flag for test

* Fix parallel test setup

In the previous patches we were attempting to use
unittest.mock.patch.dict to override the env variable used to control
parallel execution in qiskit. However, the issue with doing this is that
the env variable is read at import time and stored in a global variable
as we don't expect the env variable to change dynamically during the
execution of a script. To workaround this the mocks are removed and
instead a setUp() method is added to the test class to override the
whatever the environment default is and instead hardcode parallel_map to
run in parallel for the test and then switch it back to the earlier
value after the test finishes. This lets us dynamically adjust the
default behavior for parallel execution for this test class.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-20 14:40:13 +00:00
Matthew Treinish ffabc2e844
Make UnrollCustomDefinitions pass target aware (#8784)
* Make UnrollCustomDefinitions pass target aware

This commit makes the UnrollCustomDefinitions transpiler pass target
aware. A new kwarg, target is added to the pass constructor and if
specified the Target object passed in is used to check if the target
backend supports the gates in the circuit instead of the basis_gates
list.

Part of #7113

* Apply suggested doc fixes from code review

Co-authored-by: Kevin Hartman <kevin@hart.mn>

* Simplify custom gate detection logic in pass

This commit simplifies and deduplicates the logic for the pass around
detecting whether a particular instruciton is supported.

Co-authored-by: Kevin Hartman <kevin@hart.mn>

Co-authored-by: Kevin Hartman <kevin@hart.mn>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-20 00:23:20 +00:00
Christopher J. Wood 58d339aa3e
Fix Statevector.evolve and DensityMatrix.evolve for mixed dimension subsystems (#8900)
* Fix bug in OpShape.compose

* Fix bug in Statevector.evolve

Fixes bug where Statevector.evolve was reshaping subsystems incorrectly if subsystems had different dimensions.

* Add additional tests

* Add reno

* fix reno rst links

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-19 22:29:29 +00:00
Naoki Kanazawa b10c2ad296
Add singledispatchmethod to dependency (#8944)
* add singledispatchmethod to dependency

* Fixup release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-19 18:36:07 +00:00
Jake Lishman 514e383946
Fix classical-bit handling in control-flow StochasticSwap (#8906)
* Fix classical-bit handling in control-flow StochasticSwap

Previously we were expanding control-flow blocks to be full-width over
_all_ wires, and only contracting the qubits back again, without
changing the clbits given as node arguments.  This modifies the

The changes in most of the tests are necessary because the tests were
testing behaviour that should be considered incorrect.  The principal
new test of all this behaviour is the additional assertions added in
`_visit_block` in the random tests; these uniformly fail without this
patch, and succeed with it.

* Add integration tests of some post-transpile work

These are general integration tests for QPY and OpenQASM 3 dumping, with
a particular emphasis on making sure control-flow constructs don't
invalidate these two operations.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-19 16:30:46 +00:00
WQ a53fc9a1a0
fix hinton visualization bug (#8447)
* fix hinton visualization bug

* added release note for fix-hinton-bug

* remove issues and add more details

* correct set ylim

* Fix display and labelling of Hinton plot

The state labels in `plot_state_hinton` did not align with the correct
matrix entries.  This also updates the plot to display entries in the
natural "matrix" ordering, i.e. the same way that Numpy would display
the matrix if directly printed.  Previously, it was effectively a
transpose of what it should have been, with incorrect labels.

* Fixup release note

Co-authored-by: Junye Huang <h.jun.ye@gmail.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-19 00:49:34 +00:00
Jake Lishman 3bebd0f078
Fix single-bit-condition equality in QuantumCircuit and DAGCircuit (#8930)
* Fix single-bit-condition equality in QuantumCircuit and DAGCircuit

Previously, the `condition` of a given operation would not be converted
into bit indices in order do the semantic-equality checking that the
rest of the qargs and cargs get in a circuit.  This caused loose-bit
comparisons to produce false negatives.

* Improve temporary variable names

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2022-10-18 18:40:25 +00:00
Jake Lishman 64c5eb6725
Fix `BarrierBeforeFinalMeasurements` with loose bits (#8924)
We simply need to consider loose bits as well when constructing the new
DAG layer.  This isn't `DAGCircuit.copy_empty_like` because we don't
want things like metadata and global phase.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-18 03:08:38 +00:00
Matthew Treinish 3a073c7c5e
Fix handling of globally defined operations in Target (#8925)
This commit fixes the handling in the target for working with
instructions defined globally in the target. It adds handling to the
operation_names_for_qargs() and operations_for_qargs() methods to build
outputs that include globally defined operations instead of ignoring
them. Additionally the add_instruction() method is updated to validate
the input qargs to ensure that only valid qubits and qargs are allowed
to be added to the target for an instruction.

Fixes #8914

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-18 01:33:57 +00:00
Matthew Treinish 3fb8939728
Fix qpy custom ControlledGate with overloaded _define() (#8927)
This commit fixes a bug in the QPY serialization of ControlledGate
subclasses that defined custom _define() methods. The _define() method
is the typical way to provide a custom definition in Gate classes. While
ControlledGate class provides an alternative interface that handles
custom control states at initialization, but the _define() interface is
still valid even if it doesn't account for this. In #8571 we updated the
QPY serialization code to use the _definition() method directly to
correctly handle the open control case. But this fix neglected the case
where people were providing definitions via the mechanism from Gate.
This commit fixes this assumption by ensuring we load the definition
that comes from _define() which will fix the serialization of these
custom subclasses.

Fixes #8794

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-18 00:01:16 +00:00
Matthew Treinish 696e53d6c0
Deprecate lists for argument input on transpile() (#8835)
* Deprecate lists for argument input on transpile()

Right now the support for the argument broadcasting with list inputs for
various transpiler options on the transpile() function causes a
significant performance overhead to support, primarily do to how we have
to handle the multiple arguments across a parallel dispatch boundary. It
also significantly increases the code complexity of the function to
support more than one input for each argument (except circuits). The
utility of doing this type of argument handling is quite limited since a
similar result can be achieved with a for loop and would like be simpler
for users to reason about. When weighing all these factors the best path
forward is to just remove this functionality. This commit starts the
process of removing this feature by marking it as deprecated. Once the
deprecation cycle is complete we can greatly simplify the code in
transpile and primarily replace it with a call to
generate_preset_pass_manager() and passmanager.run() (the only thing I
think we'll have to handle out of band is faulty qubits defined in a
BackendProperties for BackendV1).

Related to #7741

* Update qiskit/compiler/transpiler.py

Co-authored-by: Kevin Hartman <kevin@hart.mn>

* Update qiskit/compiler/transpiler.py

Co-authored-by: Kevin Hartman <kevin@hart.mn>

* Fix release note typo

Co-authored-by: Kevin Hartman <kevin@hart.mn>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-17 21:37:58 +00:00
Jake Lishman c34e0b93dc
Fix loose-bit handling in QPY (#8928)
A typo in clbit-reconstruction was generating the incorrect number of
loose clbits in circuits that contained registers and loose bits, and
had more qubits than clbits.  A bug elsewhere in the code caused
circuits with _no_ registers to be deserialised as containing registers,
since the `QuantumCircuit(int, int)` constructor actually does produce
two registers (slightly surprisingly, perhaps).
2022-10-17 18:37:20 +00:00
Christopher J. Wood 8ccfda5a18
Fix pauli_basis deprecation (#8905) 2022-10-14 15:06:39 +00:00
Matthew Treinish 3292a03e5f
Foward port release note updates for 0.22.0 release (#8901)
As part of the 0.22.0 release process we updated the release notes on
the stable branch alone with bumping the version string for the package.
This commit forward ports those changes from the stable branch to main.
This will make it easier for us to backport any subsequent changes to
the release notes as part of a potential 0.22.1 release.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-14 12:05:47 +00:00
Edwin Navarro af459aa409
Return `DAGOpNode` from `dagcircuit.replace_block_with_op` (#8799)
* Return new_node from dagcircuit.replace_block_with_op

* Update doc string

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-13 20:34:51 +00:00
Matthew Treinish ad07847081
Fix transpile() for control flow operations with a Target/BackendV2 (#8852)
* Fix transpile() for control flow operations with a Target/BackendV2

This commit fixes an issue when compiling with circuits that have
control flow operations and are running transpile() with a BackendV2
instance or a custom Target. In these cases the transpile() operation
would fail to run because the Target didn't have a provision to
recognize a global variable width operation as part of the target.
Previously all operations in the target needed to have an instance of an
Operation so that the parameters and number of qubits could be verified.
Each of these operation instances would be assigned a unique name. But,
for control flow operations they're defined over a variable number of
qubits and all have the same name (this is a similar problem for gates
like mcx too). Not being able to fully represent the control flow
operations in a target was preventing running transpile() on a circuit
with control flow. This commit fixes this by adding support to the
target to represent globally defined operations by passing the class
into Target.add_instruction instead of an instance of that class. When
the class is received the Target class will treat that operation
name and class as always being valid for the target for all qubits and
parameters. This can then be used to represent control flow operations
in the target and run transpile() with control flow operations.

Fixes #8824

* Simplify test slightly

* Add release note

* Add coupling map target test

* Raise if instruction class and properties are both set

* Only return global gates if they exist

* Change UserWarning to a comment

* Revert change to instructions() getter

* Add release note about coupling map api change

* Fix lint and logic bug

* Add back nested while_loop to transpile() test
2022-10-12 22:40:59 +00:00
Jim Garrison 43cf42e712
Fix deprecation warning for `deprecated_functionality` (#8851)
* Fix deprecation warning for `deprecated_functionality`

* Emit the deprecation warning inline to avoid cyclic import

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-12 18:29:57 +00:00
Christopher J. Wood e6d23d5305
Fix pauli.evolve dtype casting error (#8877)
* Fix pauli phase evolve

* Update for unsigned int phases

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-12 17:06:36 +00:00
Matthew Treinish af82b4d0e1
Bump main branch version post rc tag (#8850)
* Bump main branch version post rc tag

Now that the first release candidate for the 0.22.0 release has been
tagged, the stable branch for the 0.22 series has been created and we
can start developing the 0.23.0 release on main. This commit bumps all
the version strings from 0.22.0 to 0.23.0 (and the backport branch for
mergify to 0.22) accordingly to differentiate the main branch from
0.22.*.

* Move release notes to dedicated directory too

* Update Cargo too

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-10-07 15:44:33 -04:00
Jake Lishman b5a3747f87
Remove tweedledum from macOS arm64 immediately (#8849)
In gh-8818 we prevented macOS arm64 from attempting to use tweedledum
1.1.1 as no arm64 wheels are supplied for that version.  In fact, the
"arm64" and "universal2" wheels supplied for 1.1.0 are actually
mislabelled x86_64 wheels as well, and so there is no working binary
version of tweedledum for arm64, and the sdist build process works only
rarely for most people.

Since the work of gh-8738 makes `tweedledum` _effectively_ optional for
`import qiskit` with immediate effect, and the only way to have a
working installation on M1 mac is essentially to have already manually
built `tweedledum` from source, the effects of immediately removing the
requirement from arm64 macs only should be very slight at worst, and a
good quality of life improvement for normal M1 users.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-07 15:00:16 +00:00
Jake Lishman 90b158c7e0
Modify preset pass managers for control-flow support (#8830)
* Modify present pass managers for control-flow support

This adds control-flow support to the level 0 and level 1 pass managers
directly, including neatly erroring out at runtime if the pass manager
was constructed with options that are not yet compatible with control
flow.  In general, we assume that plugins from outside of Terra are safe
for control flow - it's highly likely that this is not in fact the case,
but it's better to do things this way so an external plugin _can_
support control flow, as opposed to forbidding them from doing so.

Level 2 and level 3 both contain optimisations that are incompatible
with control flow right now, and so immediately error if an input
circuit has control flow.  The failing optimisations are ones that
involve a two-pass process of "block collection" followed by "block
replacement"; we have no updated any of the "block collection" analysis
passes to be safe for control flow, since we would also likely need to
communicate the control-flow structure through the property set, which
is not a path we're going down just yet.

In order to construct pass managers with nested flow control (e.g. the
routing-pass stages contain conditionals, but the entire routing stage
needs to be conditioned on the presence of control flow), there is a new
`PassManager` method `to_flow_controller`.  This produces a
`FlowControllerLinear` with the same content as the pass manager, such
that it can then itself be conditioned as a complete block, and embedded
into other pass managers.

* Remove unused import

* Fix nested `FlowController` instances forgetting passes

gh-6962 added support for nested `FlowController` instances.  It did
not, however, propagate any `DAGCircuit` output by its internal passes
into the transpilation loop, which meant that if a pass returned a new
DAG rather than mutating the input, the changes would be thrown away.
Similar behaviour was occuring with the pass "normalisation" step;
incorrect classes would raise an error, but if the normalisation needed
to raise a single pass to a list, the result would not be re-bound into
the nested controller.

* Reinstate `is not None` in trivial_layout conditions

* Add release notes for transpiler control-flow support

* Update out-of-date layout condition comments

* Make working/not-working split clearer in internal lookup

* Add tests of preset pass managers

* Update release notes

* Fix incorrect tests
2022-10-07 13:34:54 +00:00
Matthew Treinish 3bb60b4c1e
Fix handling of 1q gates in UnitarySynthesis with target (#8847)
This commit fixes a bug in the UnitarySynthesis pass with 1q gates and a
Target set. Previously the pass unconditionally expected that it would
only ever encounter 2 or more qubits when it was running on a node if
the target was set. This would cause a failure if it ever encountered a
1q node in the dag. This commit fixes the handling so the pass will
synthesize 1 qubit unitaries it encounters too.

Fixes #8845

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-07 00:22:07 +00:00
Matthew Treinish 50db8f5643
Fix DenseLayout when loose bits are present in input circuit (#8843)
* Fix DenseLayout when loose bits are present in input circuit

This commit fixes the DenseLayout transpiler pass to correctly handle
when an input circuit contains loose bits. Previously the pass would
incorrectly assume there was always a register in the circuit and only
construct the output layout with registers. This caused the pass to
return an empty layout if there were no quantum registers present in the
circuit, even if there were qubits in the circuit. This commit fixes
this by creating the layout per qubit and then only adding the registers
as metadata to the layout after the fact.

* Add release note
2022-10-06 18:56:16 +00:00
Matthew Treinish b7e6329a96
Fix reverse permutation for transpiled circuits in Operator.from_circuit (#8802)
* Fix reverse permutation for transpiled circuits in Operator.from_circuit

This commit fixes a bug in the Operator.from_circuit() constructor
method for Layout's generated by transpile(). The transpiler would set
the _layout property for an output circuit to be the mapping from the
input circuit's virtual qubits to the physical qubits (also the output
circuit's qubit index). This is useful for visualization and visually
tracking the permutation assuming you have the original circuit. However
for the `Operator.from_circuit()` constructor method which will reverse
the permutation caused by layout in the generated matrix this is not
sufficient information since we need to order of the original circuits
qubits. To fix this issue this commit changes the `_layout` attribute of
the QuantumCircuit class to store both the initial layout as before and
also a mapping of qubit objects to indices from the original circuit.
Using this extra information we can reliably handle the qubit
permutation in the constructor.

Fixes #8800

* Update bip mapper test for new _layout format

Didn't see this locally because cplex is not installed.

* Remove stray debug prints

* Use a dataclass for _layout attribute

This commit updates the _layout QuantumCircuit attribute to store a new
dataclass, TranspileLayout, which currently stores the initial_layout
used by the transpiler and the initial qubit mapping which maps the
qubit object to it's position index in the circuit. For 0.23.0 we plan
to make the circuit layout attribute public and having a proper
container class will make it easier to do this in a way where we can
evolve the interface over time if needed (likely adding a final_layout
attribute in the near future). Right now the class isn't advertised or
re-exported as the interface is still private/internal but we can make
it a public interface at the same time we add a public getter for the
circuit layout.

* Disable bogus runtime import cyclic-import pylint error

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-05 11:59:55 +00:00
Jake Lishman 5528991e17
Resolve classical conditions in `QuantumCircuit.while_loop` (#8833)
* Resolve classical conditions in `QuantumCircuit.while_loop`

This makes the behaviour match that of `if_test`; the omission here was
just a bug.

* Fix faulty while-loop tests

These tests were not previously valid; they should have been rejected
because the conditions were not actually in the circuit.
2022-10-04 17:31:12 +00:00
Matthew Treinish 86fb555871
Add support for custom backend transpiler stages (#8648)
* Add support for custom backend transpiler stages

This commit adds initial support to the transpiler and backend
interfaces for backends to specify custom transpiler stages. There are
often specific hardware compilation requirements that a general purpose
transpiler's preset pass manager can't account for. While we strive to
provide interfaces to outline all the hardware constraints via the
Target class and general purposes passes to fit and optimize an input
circuit to the target backend there are some constraints that aren't
easily addressed in a general purpose way. For such cases having an
interface for a specific backend which has the necessary context of its
own constraints to provide custom compilation steps to integrate into
the pipeline is a necessary feature. The two initial examples of this
are custom basis gate translation and custom scheduling. This commit
adds two new hook point methods for BackendV2 objects,
get_post_translation_stage() and get_scheduling_stage(). These allow
for backends to specify custom PassManager objects that will run after
the translation stage and for the scheduling stage by default when
compilation is targetting the backend. This should enable backends with
custom hardware specific requirements to influence the compilation
process so that any required custom steps to ensure the output circuit
is executable. In the future we may add additional hook points in a
similar manner to enable backends to assert more hardware-specific
compilation where the need arises.

Closes #8329

* Remove stray optimization level args from pm config

* Fix tests

* Apply suggestions from code review

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Pivot backend transpiler hook points to leverage plugins

Since in qiskit-terra 0.22.0 we're adding a plugin interface for
transpiler stages already, the more natural fit for enabling backends to
inject custom passes into a pass maanger is via that plugin interface.
This commit updates the hook points to return a plugin method name that
a backend should use by default. This will provide the same level of
flexibility but also export any custom stages as standalone methods that
users can call into if they need to and also advertise the custom stage
methods along with all other installed methods.

* Apply suggestions from code review

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Update qiskit/providers/__init__.py

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Update release note

* Update qiskit/providers/backend.py

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>

* Rename transpile() option and reword doc

* Rename hook methods backend_

* Update qiskit/compiler/transpiler.py

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
2022-10-04 09:59:52 +00:00
Jake Lishman 2a8cf79fbe
Update GateDirection and checker for control flow (#8822)
* Update GateDirection and checker for control flow

These are largely straightforwards, but since each pass has essentially
two separate versions, it became simpler to refactor them out when doing
the recursion, rather than using internal closures.  As part of the
refactor, we also swap to using `Target.instruction_supported` to check
for validity - this method was added after the passes were originally
made target-aware.

* Avoid duplicate iteration through all nodes

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-01 07:43:00 +00:00
Paul Nation c701b1020d
plot_histogram now a valid histogram, plot_distribution for non-discrete data (#8762)
* updates and black

* fix for single-bar value and label

* add plot_distribution

* fix for checking for distribution classes since they dict based

* change y label to quasi-probability

* Add release note

* Update releasenotes/notes/plot-hist-797bfaeea2156c53.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Update releasenotes/notes/plot-hist-797bfaeea2156c53.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Allow all but negative distributions to plot_histogram

* just allow all

* Add PendingDeprecationWarning on plot_histogram() with a distribution input

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-01 04:40:17 +00:00
Paul Nation 5f3c9969db
Sampled expectation value for distributions (#8748)
* Add base code

* Add tests

* Add more tests

* move files to results and move imports

* fix test

* add more tests

* change from dict to counts

* Run black

* Convert sampled exp val function to rust

This commit rewrites the python implementation of the expectation value
calculation to rust. The rust implementation should be significantly
faster to compute the expectation value.

* Fix lint

* ignore cyclic import warning since inside func

* black

* Add some checks on inputs

* Add release note

* Speed up bitstring access in rust code

This commit fixes the primary bottleneck in the rust expectation value
calculation. The bit string access of the nth position previously used
in the code was O(n) and for large numbers of qubits this access could
add up in aggregate while computing the expectation value (even
with profiling overhead for 127 qubit this was still roughly .3
seconds for calling the rust function). This commit adjusts how we
access the nth character of the bit string to be O(1) and removing that
bottlneck and for 127 qubit bit string provides a ~3x speedup. The
tradeoff is that this isn't safe (in that there is potential incorrect
behavior) if someone injects random unicode characters in the bitstring.
However as this is unlikely making the change is worth it considering
the speed up. After this commit the largest bottleneck is conversion
overhead from python->rust and memory management of the temp rust
object, at ~59% of the time to run the sampled_expval_complex()
function, which is hard to workaround. Although, there might be further
tuning to reduce the time required for the remaining 41%.

* Update qiskit/result/sampled_expval.py

If this works then yes indeed.  Each operator appears to be coded differently so happy there is some overlap here

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* explain raw dict inputs

* Update test/python/result/test_sampled_expval.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Apply suggestions from code review

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>

* Make oper_table_size a const variable instead of a magic number

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-01 02:15:56 +00:00
Luciano Bello 2b8a9e0ec8
"cregbundle set to False" warning should not raised when no classical bits are involved (#8689)
* "cregbundle set to False" warning should not raised when no classical bits are involved

* add link to the issue/PR

* wrapping

* compare result

* test resull

* handle default in a consist way

* comparison

* remove warning

* set default mpl and latex

* adjust test

* Apply suggestions from code review

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-01 01:08:23 +00:00
Alexander Ivrii 389203c929
Implementing pluggable HighLevelSynthesis (#8548)
* Initial implementation of pluggable HighLevelSynthesis

* typo

* black

* fix merge error

* Reorganizing entry points for high-level-synthesis plugins based on the comments

* fixing some typos

* HLSConfig now accepts a list of methods for each operation; also allowing to specify these lists in config's __init__

* running black

* removing hls_config from __str__ in PassManagerConfig

* Adding abc interface for high-level-synthesis plugins

* improving docs and comments

* fix

* adding tests; removing print statements

* removing external test file

* remove redundant print

* Passing HLSConfig in all transpiler optimization levels

* Fix for is_parameterized as Operations don't have to support this

* Replacing node.op.copy by copy.deepcopy(node.op) to avoid Operations implementing copy method

* release notes

* adding a link to HLSConfig class

* Temporarily removing high-level-synthesis from optimization loop

* Adding example from release notes to HighLevelSynthesis documentation

* fixing random typo

* adding references to documentation:

* Further trying to improve documentation following the review comments

* removing usused import

* minor docs changes

* Docs consolidation following review comments

* added test

* fixing title underline in docs

* minor output tweaks

* Update setup.py

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-30 20:08:21 +00:00
Julien Gacon 259e14e08b
Switch to primitive support in QNSPSA (#8682)
* switch to primitive support in QNSPSA

* attempt to fix sphinx & cyclic import

* add comment about sampler passed positionally

* Update typehints

* revert import

* Apply suggestions from code review

Co-authored-by: ElePT <epenatap@gmail.com>
Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
2022-09-30 06:20:15 +00:00
Matthew Treinish 6f84c70aa2
Add BackendSampler for Sampler from an arbitrary backend (#8668)
* Add BackendSampler for Sampler from an arbitrary backend

This commit adds a new Sampler implementation to qiskit-terra,
BackendSampler. This sampler implementation enables a sampler object
to be constructed from any backend object. It can be used to enable
backends from providers that don't have native primitive implementations
(which is most providers) to leverage tooling built on primtives. The
API works exactly the same as other sampler implementations except it
takes a required argument on the constructor `backend` which is used
to specify the `Backend` object to execute circuits on.

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>

* Update qiskit/primitives/backend_sampler.py

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Remove unused method

* Update qiskit/primitives/backend_sampler.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update API for primitive interface changes

* Fix initial statevector handling in basic aer

* Fix type hints

* follow new interfaces

* remove deprecated methods

* remove deprecated methods

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-30 02:32:18 +00:00
Julien Gacon 16b5df146c
Sampler-based VQE for diagonal operators, plus QAOA (#8669)
* plain optimization works

* support for auxops

* add first round of tests

* cast to real

* lint & more tests

* add VariationalAlgo inheritance

* batching and diagonal estimator as BaseEstimator

* add gradient support

* remove gradient support for now

* fix test filename

* fix old and new batching

* fix broadcasting from a single long array

* add slsqp batch test

* Put Sampler first (no quote intended)

* Add QAOA based on primitives.

* Add QAOA based on primitives.

* force kwargs; match function names with vqe

* remove usused imports

* formatting

* remove usused imports

* Apply suggestions from code review

Remove redundant tests and gates

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* correct docs and typehints

* Correct docstring and error text

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* update docstrings

* add callback to samplingvqe

* fix merge conflicts

* remove edit to base estimator

* formatting

* update _run for DiagonalEstimator based on BaseEstimator updates

* remove unused import

* bring sampling vqe in line with vqe

* fix docstring indentation

* Correct copyright/

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Fix copyright.

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Use QuasiDistribution typehint, rather than Mapping.

* add callback test fro sampling vqe

* Test initial point is used for QAOA

* formatting

* Test scipy optimizer callable

* Test QAOA with random initial point

* update samplingvqe and qaoa docstrings and add releasenote

* add release note for SamplingVQE and QAOA

* fix hyperlink in docstring

* fix typehints, docstrings, errors

* Convert baseoperator operators inside qaoa

* repeat all SamplingVQE tests with BaseOperator and PauliSumOp instances

Co-authored-by: Declan Millar <declan.millar@ibm.com>
Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 23:45:01 +00:00
Jake Lishman 0d1bea0398
Add control-flow support to "properties" transpiler passes (#8763)
* Add control-flow support to "properties" transpiler passes

This adds control-flow support to the `DAGCircuit` methods `depth` and
`size`, to `QuantumCiruit.depth`, and to the transpiler pass
`ContainsInstruction`.  Together, these are the basis of the principal
transpiler passes that calculate properties of circuits for other
passes.

Depth and size are not fully defined for control-flow operations, so
these methods return hints to the value.

* Fix condition-bit handling

* Add comment on recursive call in QuantumCircuit.depth

This also removes the `weight` parameter, since it's not really required
- it's simpler just to do the multiplication where the control-flow
blocks are encountered.

* Refuse to provide depth and size hints for control-flow by default

Since `depth` and `size` do not have exact meanings once control flow is
present, we decided to have the default for the public methods on
`QuantumCircuit` and `DAGCircuit` be "raise an error" if control flow is
present, and have the user specifically ask for it to get the new
hinting behaviour.  The transpiler passes always use the new hints,
because they always need to account for the inner operations when
evaluating the quality of the output of an optimisation pass.

* Add release note

* Revert changes to `QuantumCircuit.depth`

We decided to avoid putting these user-facing changes onto
`QuantumCircuit` for the initial release, when we don't have time to
also make all the other "properties" methods of `QuantumCircuit`
control-flow recursive.  I originally made the changes this way because
it was simpler for me when making the `DAGCircuit.depth` call
recursive, but due to how the caching in the `weight_fn` evolved over
the course of that implementation, the `DAGCircuit` method can be made
directly recursive.

* Rewrite release note

Co-authored-by: Kevin Krsulich <kevin.krsulich@ibm.com>

* Update documentation

Co-authored-by: Kevin Krsulich <kevin.krsulich@ibm.com>

* Make `DAGCircuit.depth` directly self-recursive

In a previous iteration of this implementation, we called
`QuantumCircuit.depth` and had that be the directly recursive call.
Since we chose not to expose control-flow modifications to the
`QuantumCircuit.{depth,size,count_ops}` methods (being more
user-visible, and the concepts aren't fully defined), this meant the
`DAGCircuit` method needed to become recursive itself.

* Swap `DAGCircuit.size` to sum if-else blocks, not max

* Update qiskit/dagcircuit/dagcircuit.py

* Add comment on control-flow property tests

* Fix typos

Co-authored-by: Kevin Krsulich <kevin.krsulich@ibm.com>

* Add recurse kwarg to analysis passes

* Make error message more descriptive

Co-authored-by: Kevin Krsulich <kevin.krsulich@ibm.com>
Co-authored-by: ewinston <ewinston@us.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 19:52:36 +00:00
Takashi Imamichi 5b35a3d386
Remove a validation check of circuits for `BaseSampler` (follow-up of #8678) (#8708)
* relax a check of measurements for Sampler

* fix a test

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 14:13:13 +00:00
Manoel Marques 837d4edffb
Pending deprecate algo eigen_solvers (#8651)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 12:43:15 +00:00
ElePT bebc1f8bbf
Implement eigensolvers (VQD) with primitives (#8640)
* New eigensolver namespace

* Add unittests

* Remove unit test

* Progress

* Revert vqd changes

* Restore temporary changes

* Change test names

* Code cleanup

* More cleanup

* Remove run options

* Fix seed test callback

* Add warning gradients

* Fix style

* Move aux ops evaluation to vqd

* Make black

* Fix cyclic imports

* Fix style unit tests

* Remove eigenstate from result class

* Add eigenstates to init

* Fix black

* Add NumPyEigensolverResult

* Fix lint

* Add eigensolvers with primitives (VQD)

* Update base class

* Update numpy eigensolver

* Apply changes VQE

* Update

* Add TODO

* Remove opflow code

* Update copyright

* Change run_options

* Add obs.eval, fix bug, add unit test, apply comments

* Fix black

* Fix attributes, remove gradient

* Remove defaults

* Fix lint, add base operator support

* Add BaseOperator support and unit tests

* Fix style

* Fix style

* Fix lint

* Fix sphinx

* Update qiskit/algorithms/eigensolvers/vqd.py

* Update qiskit/algorithms/eigensolvers/vqd.py

* Apply VQE changes

* Add metadata to result

* Fix old reno cross reference

* fix lint

* modify aux ops metadata

* Add metadata to callback

* Return metadata in observables evaluator

* fix copyright

* Update test/python/algorithms/test_numpy_eigen_solver.py

* Remove opflow from vqd tests

* Add optimizer result

* fix tests

* Fix lint

* Fix black

* Fix cyclic imports

* Fix black againnn

* Add minimally working VQE with estimator primitive implementation.

No gradients, no tests etc.

* Revert from dataclass results to original result classes.

* Enforce positional and keyword VQE arguments.

* Move aux op eval logic to function

* Update docstring.

* Remove max_evals_grouped. Force to set directly on optimizer.

* Remove validate min import.

* Make note that eval_observables will be used to eval aux ops.

* Add initial vqe tests.

* Have VQE inherit from VariationalAlgorithm.

* Move energy evaluation to unnested function.

* Construct h2_op using SparsePauliOp

* Add gradient with primitives support.

* Update docstrings

* update broadcast handling

* update eval_energy output for batching

* add incomplete QNSPA test

* fix batch evaluation of QNSPSA test

* remove vqe callback

* move estimator to first arg

* remove usused imports

* add minimum eigensolvers test init file

* add aux ops tests and prepare for new eval_operators

* no longer support account for Nones in aux_ops

* correct typing for MinimumEigensolver

* Compute default initial point using ansatz bounds.

* Add NumPyMinimumEigensolverResult

* Fix type hints

* Fix type hints

* Formatting

* Do not store NumPyMES result inside the algo.

* Provide default values for ansatz and estimator

* Formatting

* fix old and new batching

* Add tests for NumpyMES and import in module.

* Use lazy formatting in log messages

* Use lazy formatting in log messages

* Add back callback to VQE.

* minor renaming

* raise algorithm error if primitive jobs fail

* Add return documentation

* Improve var names and docstrings.

* Apply suggestions from code review

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: dlasecki <dal@zurich.ibm.com>

* minor formatting

* minor formatting

* Ensure evaluate_energy/gradient match

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* return bounds logic; fix some docstrings and minor refactor

* Force keyword arguments in vqe.

* Use estimate_observables function

* break up numpy mes tests with subTest

* formatting

* remove redundant eval_aux_ops

* add typehints to docstring attributes

* remove usused imports

* remove default ansatz

* remove usused imports

* update typehints

* avoid changing the original ansatz

* avoid changing the original ansatz

* create separate function to build vqe result

* Correct aux operator eignvalue type hint

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* add variance to callback

* use std_dev in callback rather than variance

* formatting

* return variance and shots in callback

* return full metadata in callback

* Move validation functions to algorithms/utils

* correct the callback attribute documentation

* correct the callback attribute typehint docstring

* update VQE docstring

* release note and pending-depreciate old algs

* update vqe class docstring

* Apply suggestions from code review

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* Do not copy ansatz

* Note pending depreciation of old algs

* fix docstrings and imports

* Fix issues with building docs

* Include OptimizerResult in VQEResult

* Remove trailing whitespace

* Fix math notation in docstring

* estimate_obervables to return metadata @ElePT +VQE

* add example in release note

* Update evaluate_observables docstring

* Fix observables_evaluator tests.

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* fix trotter_qrte tests and remove depreciation

* formatting

* remove unused import

* Apply suggestions to docstring from code review

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update VQE docstring

* Remove printing

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* Add parameters to estimate observables

* Fix estimate obs. unit test

* Update arg description

* Update arg description

* keep equation part of sentence

* dict -> dict[str, Any]

* Update qiskit/algorithms/optimizers/spsa.py

Apply suggestion Imamichi-san

* introduce FilterType and aux_operator_eigenvalues -> aux_operators_evaluated

* Correct typehint

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>

* Adapt to VQE

* Update qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py

* Pull from main

* Remove change vqe

* Refine docs, typehints, remove opflow

* add check for PauliSumOp

* Fix import

* reformat test

* Remove metadata unit tests

* Add operator tests

* Reformat tests

* Fix observables eval test

* Apply initial feedback

* Change numpy eig. aux ops metadata

* Apply review comments

* Fix unittests

* Update reno

* Apply review comments

* Fix result names, typehints

* Fix docs

Co-authored-by: Manoel Marques <manoel.marques@ibm.com>
Co-authored-by: Declan Millar <declan.millar@ibm.com>
Co-authored-by: dlasecki <dal@zurich.ibm.com>
Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 11:22:17 +00:00
Ikko Hamamura 17de3b0b78
Clifford does not use StabilizerTable as internal data and PendingDeprecation of PauliTable and StabilizerTable (#7269)
* initial commit

* Update clifford and stabilizerstate

* fix lint and tests

* fix test

* Deprecate StabilizerTable

* Remove autogenerated file

* update docs

* refactoring

* improve random_clifford

* add phase_stab, phase_destab

* rename phase_stab to stab_phase

* add Clifford.symplectic_matrix method

* remove deprecation

* fix __setitem__

* add pending deprecation to PauliTable

* update releasenote

* update releasenote

* refactor

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 09:06:37 +00:00
Matthew Treinish 594ad019a3
Remove pulse defaults for old fake 20q backends (#8665)
* Remove pulse defaults for old fake 20q backends

The pulse defaults payload for the almaden, johannesburg, and singapore
fake backends are collectively taking up > 50% of the total disk
footprint of an installed copy of Qiskit. This is because the pusle
defaults for these backends predate the use the of parameterized pulse
definitions and contain arrays of sampled waveforms for the pulse
definitions. This exceedingly large file size slows down the entire
package and and makes it slower to install. When weighing the potential
value these defaults files provide for simulating and compiling with
pulse awareness for long retired devices against the real cost of
having the files included in the package there isn't a reason to keep
the files in the tree any longer. This commit removes the pulse
defaults files for these fake backends to greatly shrink the installed
package size of qiskit-terra.

* Update releasenotes/notes/remove-pulse-defs-old-20q-4ed46085b4a15678.yaml

* Update tests and docs

Several tests and docs were relying on the pulse data being present in
the fake backends. This commit updates the tests and docs to avoid this
and either rely on different fake backends that use parametric pulses or
not rely on a fake backend at all. In one case a bug is fixed the
assembler which was causing the tests to incorrectly pass because the
use of pulse backends without parametric pulses was masking incorrect
behavior.

* Revert passmanager config string test changes

* Remove self.maxDiff in str test

* Fix missing backtick

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 04:47:14 +00:00
Matthew Treinish 0cd7dba184
Use Sabre by default for optimization levels 1 and 2 (#8552)
* Use Sabre by default for optimization levels 1 and 2

This commit updates the preset pass manager construction to use the
SabreLayout and SabreSwap passes by default for optimization level 1 and
level 2. With the recently merged #7977 the performance of the sabre
swap pass has improved significantly enough to be considered for use by
default with optimization levels 1 and 2. While for small numbers of
target device qubits (< 30) the SabreLayout/SabreSwap pass doesn't quite
match the runtime performance of DenseLayout/StochasticSwap it typically
has better runtime performance for larger target devices. Additionally,
the runtime performance of Sabre should also improve further after #8388
is finished. However, the output quality from the sabre passes is
typically better resulting in fewer swap gates being inserted. With the
combination of better quality and comparable runtime performance it
makes sense to use sabre as the default for optimization levels 1 and 2.
For optimization level 0 stochastic swap is still used there because we
want to continue to leverage TrivialLayout for that level and to get
the full quality advantages SabreSwap and SabreLayout should be used
together.

* Fix pickling of SabreSwap object

In #7977 we moved to use compiled objects for part of the SabreSwap
compiler pass. However an unintended side effect of that PR was the use
of Rust objects stored in instance level variables which weren't
pickleable. This breaks multiprocessing at the PassManager level which
expects to be able to pickle and send a SabreSwap object to the
subprocess running on a circuit. This commit fixes this by making the
Rust NeighborTable object pickleable and switching to storing the
heuristic string at the instance level instead of the heuristic enum.

* Update layout tests to match new default

This commit updates a failing layout test which was assuming that level
1 and level 2 where still running DenseLayout. The test has been updated
to reflect the new default of SabreLayout.

* Fix stochastic swap specific test to use that routing method

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 03:43:28 +00:00
Jake Lishman fca3864951
Add conversion transpiler pass from `c_if` to `IfElseOp` (#8764)
* Add conversion transpiler pass from c_if to IfElseOp

This is intended to be used to ease the transition from the old-style
conditions to the new-style form.  Backends may use it in their custom
pipelines, so they can guarantee they only need to deal with one form.

A further classical optimisation may be to group `IfElseOp` blocks that
share the same condition into a single operation, but this would likely
be a separate pass, if added, or potentially be the domain of a separate
part of the circuit-description/compilation/running pipeline.

* Remove nondeterministic bit ordering

* Add test of no-op behaviour

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 02:39:09 +00:00
Ikko Hamamura 2b7282d476
Parameter handling in SparsePauliOp (#8620)
* Parameter-friendly usage of Numpy methods

* remove pdb.set_trace()

* Updated target image in mpl backend visualization tests

* Fixed methods causing failing tests

* fixed lint

* Fixed formatting of variable in SparsePauliOP

* Fixed dtype casting (object->float, complex->float) tests

* Fixed failing tests

* Fixed lint

* Fixed import order for linter

* revert gate.py

* revert qdrift.py

* revert PauliSumOp

* update SparsePauliOp

* readable code (Jake's suggestion)

* add tests

* add docs

* fix docs

* fix typo

* add reno

* Update documentation

* use-parameters

* bind_parameters_to_one

Co-authored-by: Jesus Sistos <jesussistos.josb@gmail.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-28 23:59:48 +00:00
Freya Shah 368fbbb702
Migrating AdaptVQE to Qiskit Terra (#7930)
* added adapt_vqe

* implemented  most of the suggested changes

* implemented the suggested changes

* added the changes

* .

* made the suggested changes

* added the code

* test added

* added adapt_vqe

* .

* .

* added changes

* added changes

* added changes

* .

* added the changes

* .

* added

* formatting done

* Update adapt_vqe.py

* made the suggested changes

* made the changes

* lint changes

* removed initial point from init

* black changes

* added inline definition

* made the changes

* removed sys import

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* Update qiskit/algorithms/minimum_eigen_solvers/adapt_vqe.py

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* added

* added

* .

* .

* made final changes

* fix: evaluate gradients via commutator relation

The gradients for the operators in an `EvolvedOperatorAnsatz` can
actually be evaluated via simple measurements on the current circuit
without having to construct the new ansatz for every single excitation
during every iteration. Instead, the gradients can be computed from the
commutator of the excitation operators with the main operator of the
VQE.
Doing so, results in a drastic performance improvement.

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* .

* made the changes

* .

* fix: AdaptVQE gradient computation unittest

* fix: remove unused import

* refactor: migrate AdaptVQE to primitive-based module

* Add a release note

* Apply suggestions from code review

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Pass parameters to estimate_observables method

Co-authored-by: Declan Millar <declan.millar@ibm.com>

* Apply suggestions from code review

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* More changes based on code review

* Avoid deep-copying the ansatz

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>
Co-authored-by: Max Rossmannek <oss@zurich.ibm.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: Declan Millar <declan.millar@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-28 19:38:52 +00:00
Matthew Treinish 4a857f6114
Add BackendV2Converter class for treating BackendV1 as BackendV2 (#8759)
* Add BackendV2Convert class for treating BackendV1 as BackendV2

This commit adds a new class BackendV2Converter which is a BackendV2
implementation that converts an input BackendV1 object into a BackendV2
implementation. This is useful for users that are supporting working
with arbitrary providers so that they can standardize on using the
newest access patterns even if a provider is still using BackendV1.
Similarly, for qiskit's internal usage, this gives us a path to move all
of the transpiler internals to use Target and avoid carrying around
duplicate information in the PassManagerConfig for passes that haven't
been updated. This will enable us to convert input BackendV1 instances
to a target once on initial calling and have the transpiler only ever
see a target.

Fixes #8611

* Update docstring

* Return empty options for _default_options

* Remove leftover pylint disable

* Expand standard gate conversions and handle missing basis_gates

* Fix copy paste error qubit_props_list_from_props() docstring

* Add name mapping argument to allow setting custom name-> gate mappings for conversion

* Add missing gamma parameter

* Fix handling of global ops in configuration

* Raise exception on custom gates without mapping

* Move name mapping to standard gates module

* Fix lint and docs

* Use gate object name attribute to build name mapping

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>

* Fix lint

* Fix pylint cyclic-import error

* Update qiskit/providers/backend_compat.py

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>

* Remove supported_instructions and add option for adding delay

The supported instructions field is underdocumented and it's not clear
that the instructions it contains are something that we want to support
directly. Since the only reason we added support for it in the target
generation was to handle the delay for ibm backends (mostly in tests as
the IBM provider will be using BackendV2 natively soon) this commit
removes its usage and adds a new flag for explicitly adding delay to the
backend's target.

* Add mention of converter class to API changes section

* Add missing flag usage to delay test

* Run black

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2022-09-28 06:37:53 +00:00
Manoel Marques 293ab43afb
Pending deprecate algorithms (#8703)
* Pending deprecate algorithms

* Update releasenotes/notes/pending-deprecate-min-eigen-solvers-fa4341e1014e4df0.yaml

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-27 20:44:09 +00:00
Declan Millar 037ae6375e
VQE implementation with estimator primitive (#8702)
* Add minimally working VQE with estimator primitive implementation.

No gradients, no tests etc.

* Revert from dataclass results to original result classes.

* Enforce positional and keyword VQE arguments.

* Move aux op eval logic to function

* Update docstring.

* Remove max_evals_grouped. Force to set directly on optimizer.

* Remove validate min import.

* Make note that eval_observables will be used to eval aux ops.

* Add initial vqe tests.

* Have VQE inherit from VariationalAlgorithm.

* Move energy evaluation to unnested function.

* Construct h2_op using SparsePauliOp

* Add gradient with primitives support.

* Update docstrings

* update broadcast handling

* update eval_energy output for batching

* add incomplete QNSPA test

* fix batch evaluation of QNSPSA test

* remove vqe callback

* move estimator to first arg

* remove usused imports

* add minimum eigensolvers test init file

* add aux ops tests and prepare for new eval_operators

* no longer support account for Nones in aux_ops

* correct typing for MinimumEigensolver

* Compute default initial point using ansatz bounds.

* Add NumPyMinimumEigensolverResult

* Fix type hints

* Fix type hints

* Formatting

* Do not store NumPyMES result inside the algo.

* Provide default values for ansatz and estimator

* Formatting

* fix old and new batching

* Add tests for NumpyMES and import in module.

* Use lazy formatting in log messages

* Use lazy formatting in log messages

* Add back callback to VQE.

* minor renaming

* raise algorithm error if primitive jobs fail

* Add return documentation

* Improve var names and docstrings.

* Apply suggestions from code review

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: dlasecki <dal@zurich.ibm.com>

* minor formatting

* minor formatting

* Ensure evaluate_energy/gradient match

Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>

* return bounds logic; fix some docstrings and minor refactor

* Force keyword arguments in vqe.

* Use estimate_observables function

* break up numpy mes tests with subTest

* formatting

* remove redundant eval_aux_ops

* add typehints to docstring attributes

* remove usused imports

* remove default ansatz

* remove usused imports

* update typehints

* avoid changing the original ansatz

* avoid changing the original ansatz

* create separate function to build vqe result

* Correct aux operator eignvalue type hint

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* add variance to callback

* use std_dev in callback rather than variance

* formatting

* return variance and shots in callback

* return full metadata in callback

* Move validation functions to algorithms/utils

* correct the callback attribute documentation

* correct the callback attribute typehint docstring

* update VQE docstring

* release note and pending-depreciate old algs

* update vqe class docstring

* Apply suggestions from code review

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* Do not copy ansatz

* Note pending depreciation of old algs

* fix docstrings and imports

* Fix issues with building docs

* Include OptimizerResult in VQEResult

* Remove trailing whitespace

* Fix math notation in docstring

* estimate_obervables to return metadata @ElePT +VQE

* add example in release note

* Update evaluate_observables docstring

* Fix observables_evaluator tests.

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* fix trotter_qrte tests and remove depreciation

* formatting

* remove unused import

* Apply suggestions to docstring from code review

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update VQE docstring

* Remove printing

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* Add parameters to estimate observables

* Fix estimate obs. unit test

* Update arg description

* Update arg description

* keep equation part of sentence

* dict -> dict[str, Any]

* Update qiskit/algorithms/optimizers/spsa.py

Apply suggestion Imamichi-san

* introduce FilterType and aux_operator_eigenvalues -> aux_operators_evaluated

* Correct typehint

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>

* update vqe docstring and use old typing for type alias

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: dlasecki <dal@zurich.ibm.com>
Co-authored-by: Max Rossmannek <max.rossmannek@uzh.ch>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: ElePT <epenatap@gmail.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
2022-09-27 13:43:40 +00:00
Naoki Kanazawa 672e95d089
Remove symbolic pulse subclass implementation (#8278)
* Remove symbolic pulse subclass implementation. Now every symbolic pulse objects are SymbolicPulse instance. Subclasses become SymbolicPulse factory, and isinstance check is invalidated because these classes are never instantiated. QPY loader for these classes are also removed.

* Review comments

Co-authored-by: Will Shanks <willshanks@us.ibm.com>

* comments from review

* update release note

* fix test

Co-authored-by: Will Shanks <willshanks@us.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-27 02:23:59 +00:00
Alexander Ivrii 2f6ea4b87f
Improving memory consumption of DagDependency when lists of transitive predecessors and successors are not required (#8525)
* Improved construction of DagDependency when lists of transitive successors and predecessors are not needed

* typos

* minor

* Adding TODO and explanation messages following review comments

* Update releasenotes/notes/dag_dependency_speedup-f6298348cb3d8746.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-26 21:33:39 +00:00
Manoel Marques ae0ceee6ea
Rewrite Amplitude Estimators with Primitives (#8656)
* Rewrite Amplitude Estimators with Primitives

* Update qiskit/algorithms/amplitude_estimators/ae.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* fix errors

* Update qiskit/algorithms/amplitude_estimators/ae.py

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* Update qiskit/algorithms/amplitude_estimators/fae.py

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* Update qiskit/algorithms/amplitude_estimators/fae.py

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* Update qiskit/algorithms/amplitude_estimators/iae.py

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* fix annotations

* Add sampler properties

* refactor evaluate_measurements

* deprecate qiskit.pulse.utils.deprecated_functionality in favor of qiskit.utils.deprecation.deprecate_function (#8696)

* deprecate deprecated_functionality

* pylint: disable=cyclic-import

* Add reno

* Include Terra version in deprecation notice

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>

* feat: support sum(LinearMixin) (#8722)

* feat: support sum(LinearMixin)

This enables the use of `sum(...)` for subclasses of the `LinearMixin`
class. It also adds the reflective operand dunder methods `__radd__` and
`__rsub__`.

* Add crossreferences to release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>

* set shots on fae sampler

* cache circuits during estimate

* Change algos estimate

* Change from run_options ro options

* remove circuits cache list

* Update qiskit/algorithms/amplitude_estimators/ae.py

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* Update qiskit/algorithms/amplitude_estimators/ae_utils.py

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* change slice

* Get shots from metadata

* Update qiskit/algorithms/amplitude_estimators/iae.py

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* Rearrange annotation None

* Update qiskit/algorithms/amplitude_estimators/ae.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Fix deprecation msg

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: dlasecki <dal@zurich.ibm.com>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Max Rossmannek <oss@zurich.ibm.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-24 00:24:10 +00:00
dlasecki 4c1042e4cc
Quantum Phase Estimation algorithms with primitives. (#8666)
* Added samplers in place (draft)

* Implemented unit tests with primitives.

* Implemented unit tests with primitives. Updated typhints.

* Added exception handling for sampler.

* add pending deprecation msgs

* Added code review suggestions.

* Added release notes.

* Added release notes.

* Removed shots argument.

* Implemented CR suggestions.

* Removed shots.

* Drafted the usage of EvolutionSynthesis.

* Applied some CR comments.

* Updated reno.

* Extended bound calculation to other types.

* Fixed bound calculation.

* Fixed unitary calculation.

* Made unit tests work.

* Code refactoring.

* Added Mapping; code refactoring.

* Fixed SparsePauliOp handling, reduced use of opflow in new tests.

* Removed opflow from primitive version unit tests.

* Updated reno; removed dead code.

* Added Statevector unit test.

* Added Statevector unit test.

* Changed run_options to options.

* Code refactoring.

* Removed deprecated pe_circuit.

* Made types more specific.

* Lint

* Improved docs for allowed types.

Co-authored-by: Manoel Marques <manoel.marques@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-23 22:07:06 +00:00
dlasecki 13d93119ff
Implemented TrotterQRTE algorithm with primitives. (#8706)
* Implemented observables_evaluator.py with primitives.

* Added evolvers problems and interfaces to time_evolvers package.

* Mostly updated trotter_qrte.py to use primitives.

* Added observables_evaluator.py that uses primitives.

* Added observables_evaluator.py that uses primitives.

* Updated trotter_qrte.py to use primitives.

* Updated imports

* Updated typehints and limited use of opflow.

* Updated typehints and limited use of opflow.

* Removed files out of scope for this PR.

* Added annotations import.

* Added trotter_qrte.py with unit tests.

* Refactored trotter_qrte.py.

* Added observables_evaluator.py with primitives.

* Added ListOrDict support to observables_evaluator.py.

* Updated trotter_qrte.py unit tests; code refactoring.

* Included CR suggestions.

* Applied some CR comments.

* Applied some CR comments.

* Added reno.

* Added reno.

* Accepting Statevector.

* Added attributes docs.

* Support for 0 operator.

* Code refactoring.

* Updated init.

* Add pending deprecation

* Add pending deprecation for evolvers

* Code refactoring.

* Code refactoring.

* Renamed classes and linked to algorithms init.

* fix docstring

* Improved reno.

* Improved reno.

* Returning variances and shots.

* Code refactoring.

* Updated classes and applied CR suggestions.

* Added reno.

* Reduced use of opflow in tests.

* Black fix.

* Unit test fix.

* Reduced use of opflow.

* Handle empty inputs gracefully.

* Applied CR comments.

* Applied CR comments.

* Updated method names.

* Applied CR comments.

* Eliminated cyclic import.

* Drafted reduced use of opflow.

* Drafted reduced use of opflow.

* Removed use of opflow.

* Code refactoring.

* Addressed CR comments.

* Added more tests for error paths.

* Added Trotter section in algorithms init.

* Changed init.

* Apply suggestions from code review

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Co-located TrotterQRTE with time evolvers in docs.

Co-authored-by: Manoel Marques <Manoel.Marques@ibm.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-23 20:46:47 +00:00
Luciano Bello cb715a34d9
Fix for `None` in `state_to_latex` latex output (#8273)
* term might be None

* Test

Co-authored-by: Rishabh Chakrabarti <rishacha.dev@gmail.com>

* a better solution

* simpler example

* reno

* rounding

* remove _round_if_close

* black

* revert test

* black

* max_size

* max_size -> decimals

* max_siz=0 -> decimals=10

Co-authored-by: Rishabh Chakrabarti <rishacha.dev@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-23 16:48:12 +00:00
a-matsuo b7d5f4af39
Support `Sampler` in `Grover` (#8647)
* wip added sampler

* added sampler

* fix lint

* assert warns

* fix reno

* Add deprecation

* fix unit tests for pending deprecation

* remove unnecessary jupyter notebook

* add pend.deprecation test

* Update qiskit/algorithms/amplitude_amplifiers/grover.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* added error handling

* fix

* use algorithm error

* fix lint

* fix

* Update qiskit/algorithms/amplitude_amplifiers/grover.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update qiskit/algorithms/amplitude_amplifiers/grover.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* filter warnings

* added unittests

* lint

* fix

* fix

* fix

* fix

* fix

* lint

* remove print

* update sampler's options

* changed the shots test to TODO

* lint

* added _prepare_grover in the unittest

* fix test

* changed the code-block in the release note

* Update releasenotes/notes/add-grover-primitives-10f81efdba93703d.yaml

* Update qiskit/algorithms/amplitude_amplifiers/grover.py

* Update qiskit/algorithms/amplitude_amplifiers/grover.py

* Apply suggestions from code review

* Apply suggestions from code review

* Apply suggestions from code review

Co-authored-by: Manoel Marques <manoel.marques@ibm.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-22 23:44:27 +00:00
dlasecki cde535cf3d
Implemented PVQD algorithm with primitives. (#8705)
* Implemented observables_evaluator.py with primitives.

* Added evolvers problems and interfaces to time_evolvers package.

* Mostly updated trotter_qrte.py to use primitives.

* Added observables_evaluator.py that uses primitives.

* Added observables_evaluator.py that uses primitives.

* Updated trotter_qrte.py to use primitives.

* Updated imports

* Added estimator to pvqd.py (draft)

* Updated typehints and limited use of opflow.

* Updated typehints and limited use of opflow.

* Removed files out of scope for this PR.

* Added annotations import.

* Added observables_evaluator.py with primitives.

* Added ListOrDict support to observables_evaluator.py.

* Drafted pvqd.py with the fidelity primitive; type hints updated.

* Accepting fidelity primitive.

* Included CR suggestions.

* Applied some CR comments.

* Applied some CR comments.

* Added reno.

* Added reno.

* Accepting Statevector.

* Added attributes docs.

* Support for 0 operator.

* Implemented pvqd unit tests with primitives; code refactoring.

* Added reno.

* Updated algorithms init.

* Code refactoring.

* Removed old pvqd algorithm and related files.

* Add pending deprecation for evolvers

* Renamed classes and linked to algorithms init.

* fix docstring

* Improved reno.

* Updated classes names.

* Code refactoring.

* Applied CR comments.

* Removed unnecessary files.

* Applied CR comments.

* Black fix.

* Applied CR comments.

* Init updates.

* Reduced number of cyclic import.

* Fix for cyclic import

* Doc fix

* Updated init.

* Added error raising and unit test.

* Apply suggestions from code review

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Fixed code example.

Co-authored-by: Manoel Marques <Manoel.Marques@ibm.com>
Co-authored-by: woodsp-ibm <woodsp@us.ibm.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-22 19:06:14 +00:00
Pieter Eendebak 0f688eb305
Fix flipping of gate direction in transpiler for CZ gate (#8625)
* fix flipping of the symmetric cz gate

* complete test

* black

* pylint

* black

* add release notes

Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com>
2022-09-22 13:52:08 +00:00
Takashi Imamichi 007cc25bc4
Update `ProbDistribution` and `QuasiDistribution` to store the number of bits if bitstrings w/o prefix are given (#8464)
* Update ProbDistribution and QuasiDistribution to store data as bit-strings

* fix sampler tests

* Revert the internal data from bitstrings to integers

* Store the information of number of bits when bitstrings w/o prefix,
  e.g., "00101", are given.

* update reno

* Revised `num_bits`, comments, and tests.

Co-authored-by: Julien Gacon <gaconju@gmail.com>

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Paul Nation <nonhermitian@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-22 02:45:05 +00:00
Ryan Hill 418b7cc802
add state_to_latex prefix kwarg (#8461) 2022-09-21 23:37:26 +00:00
Manoel Marques f94647212d
Fix release notes code block format (#8777) 2022-09-21 18:39:24 +00:00
Takashi Imamichi db53e46cb2
Remove `parameters` arguments for `run` method of Primitives (#8684)
* remove `parameters` arguments for `run` method

* fix lint

* update docstring and reno

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-21 15:51:39 +00:00
Luciano Bello 4f650581f2
adding FakeGeneva (#8322)
* conf_geneva

* reno

* adding to the test

* order

* calibration data 2022-07-12 15:40:30+02:00

* calibration from 2022-06-24 23:00:30+02:00

* Update releasenotes/notes/ibm_geneva-5b1e9308dc302e2e.yaml

* remove v1

* reno new

Co-authored-by: Junye Huang <h.jun.ye@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-20 18:55:36 +00:00
Matthew Treinish c0f5ae02a9
Fix handling of holes in physical bits list in Layout (#8767)
* Fix handling of holes in physical bits list in Layout

Previously the behavior of `Layout.add(virtual)` would attempt to select
an available physical bit to pair for the layout. However, the manner in
which this selection was done was buggy and it would potentially skip
over available physical bits on the device and instead add a new
physical bit to the layout. This had unintended consequences for layouts
that added bits in higher numbers first. This commit fixes this behavior
by first checking that we've exhausted all available physical bits from
0 to max bit in layout. Then if there are no holes in the physical bits
in the layout it will add a bit to the top.

Fixes #8667

* Add release note and clarify docstring

* Apply suggestions from code review

Co-authored-by: Jake Lishman <jake@binhbar.com>

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-20 17:35:45 +00:00
Luciano Bello b454a8dfcb
Add FakeAuckland backend to fake provider (#8467)
* adding FakePerth

* Update releasenotes/notes/ibm_perth-5b1e9308dc302e2e.yaml

* adding FakeAuckland

This PRs adds FakeAuckland based on ibm_auckland.

* V1 removed

* Mock over Fake

* remove V1

* removing v2

* remove v2 name

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-19 13:30:59 +00:00
Luciano Bello 4b5a5bf45e
Add FakeOslo backend to fake provider (#8358)
* adding FakeOslo

* Update releasenotes/notes/fake_oslo-7bba98d7269f959b.yaml

* only v2

* put FakePerth back
2022-09-19 12:01:23 +00:00
Luciano Bello cdfd66ef2e
adding FakePerth (#8344)
* adding FakePerth

* Update releasenotes/notes/ibm_perth-5b1e9308dc302e2e.yaml

* Mock over Fake

* remove V1

* removing v2

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-16 22:45:42 +00:00
Paul Nation e4381c3760
Default set to turn off approximation_degree (#8595)
* Default set to turn off approximation_degree

* Add a release note

* spelling

* convert to upgrade note

* Update releasenotes/notes/turn-off-approx-degree-df3d39eb69f7f09f.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Update releasenotes/notes/turn-off-approx-degree-df3d39eb69f7f09f.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Update releasenotes/notes/turn-off-approx-degree-df3d39eb69f7f09f.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Update releasenotes/notes/turn-off-approx-degree-df3d39eb69f7f09f.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Update releasenotes/notes/turn-off-approx-degree-df3d39eb69f7f09f.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-16 21:14:03 +00:00
Jake Lishman e76ab71562
Prepare for removal of `tweedledum` as a requirement (#8738)
* Prepare for removal of `tweedledum` as a requirement

This adds the necessary optional-functionality checker
(`HAS_TWEEDLEDUM`), converts all Terra uses of `tweedledum`-dependent
functionality to be gated on lazy checker, and deprecates the implicit
import of `tweedledum`-specific functionality in `qiskit.circuit`.  This
commit does not remove `tweedledum` as a requirement just yet; we are
waiting one Terra release to give downstream users a chance to adjust.

* Fix lint

* Fix import paths

* Fix straggler release note

* Update releasenotes/notes/begin-tweedledum-removal-25bb68fc72804f00.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-16 19:58:00 +00:00
Iman Elsayed 3ae23373e0
Fix printing an empty PauliList (#7712)
* add num.qubits check to be _truncated_str in pauli_list.py - Resolved Issue #7359

* new file:   fix-empty-string-pauli-list-init-4d978fb0eaf1bc70.yaml
	modified:   ../../test/python/quantum_info/operators/symplectic/test_pauli_list.py

* Added test to test_array_init to test array initialization for empty array

* Run black on test_pauli_list.py

* Update releasenotes/notes/fix-empty-string-pauli-list-init-4d978fb0eaf1bc70.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-16 16:50:02 +00:00
Jake Lishman 02d2d6e705
Allow DAG-node substitution without overriding conditions (#8615)
* Allow DAG-node substitution without overriding conditions

Currently, `DAGCircuit.substitute_node_with_dag` forcibly copies any
condition on the `node` onto all the operations in the replacement DAG.
This style was because the method was originally used by the
basis-translation passes (`Decompose`, `BasisTranslator`, etc), which
did not want to have to worry about the condition.

This model of the condition being a "addition" to a node is now too
restrictive with the move to more dynamic circuits; one cannot
replace an (old-style) conditioned node with a custom instruction or an
`IfElseBlock` that implements the condition internally, for example by
taking the condition bits in the `clbits` field and using the condition
on only a subset of the definition nodes.

This commit does not add any such option to `DAGCircuit.substitute_node`;
a new interface for wire-reordering in the arguments did not appear
quite as clear to me, and this commit can stand alone.

* Inline helper functions for clearer tracebacks on error

* Slightly improve wire-mapping error messages

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-16 02:07:45 +00:00
Jake Lishman 7c04319a8c
Add internal routine for canonicalisation of control-flow builders (#8627)
* Add canonical form for control-flow builders

This adds an internal function for use in tests that puts circuits
constructed with the control-flow builders into a canonical form.  There
are several non-determinstic components to the control-flow builders,
since they internally track their resources with hashmaps, and at the
end pick an arbitrary order to sequence their arguments in.  The order
is not likely to be the same between a circuit constructed manually and
one constructed by a builder, even though they describe the same
dynamics.

For-loops with automatically generated loop variables (the
`with qc.for_loop(indices) as param: ...` form) will also vary between
circuits, as a unique parameter is constructed each time a new one is
requested to avoid collisions.  The canonicalisation routine uses a
shared iterable of parameters that always returns the exact instances in
the same order.  Replacing the loop variable with a new name has no
effect, since it is logically scoped to the loop only and the operation
is effectively lambda-calculus-like alpha conversion.

This canonicalisation routine is very slow and inefficient, so is only
intended for ease in writing tests.  Making the builders always output a
canonical order would add unnecessary overhead to them for most cases,
and the loop-parameter canonicalisation would potentially cause problems
if one control-flow built circuit was nested somehow within another
(such as by `QuantumCircuit.compose`), as the loop variables could
clash (and would violate the canonical form anyway).

* Fix non-deterministic DAGCircuit.__eq__

The bits-in-registers equality check previously constructed a sequence
of `(name, bit_indices)` tuples using the `dict.items()` iterator.  This
is unnecessarily insertion-order dependent for registers (in CPython,
non-deterministic in general).  Instead, we can compare two
dictionaries, which will correctly check key-by-key without needing the
creation order to match.

* Use canonicalisation instead of custom equivalence in builder tests

The builder tests previously used a custom circuit-equality checker,
which somewhat separated them from other circuit-equality tests.  Using
the control-flow aware canonicalisation routine first lets us rewrite
the circuit using simple rules that clearly don't change the semantics
of the circuit, and then use the regular equality checkers.

This swap over turned up a bug in the previous iteration of the tests
(in the "expected" results!), where the bits of two block bodies were
not ordered the same as the arguments to those operations.  This commit
also corrects those.

* Make initial recursive call clearer

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-15 23:54:59 +00:00
dlasecki 8bb1c01a8b
Removes old VarQTE algorithm code (without primitives). (#8750)
* Removed old VarQTE and tests.

* Removed reno

* Updated init.

* Updated init.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-15 22:39:30 +00:00
dlasecki 50f2eaa33e
Adds observable evaluator with primitives. (#8683)
* Added observables_evaluator.py with primitives.

* Added ListOrDict support to observables_evaluator.py.

* Included CR suggestions.

* Applied some CR comments.

* Added reno.

* Support for 0 operator.

* Add pending deprecation

* Code refactoring.

* Code refactoring.

* Improved reno.

* Returning variances and shots.

* Unit test fix.

* Reduced use of opflow.

* Handle empty inputs gracefully.

* Applied CR comments.

* Applied CR comments.

* Eliminated cyclic import.

Co-authored-by: Manoel Marques <manoel.marques@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-15 20:01:29 +00:00
Daniel J. Egger 4ac8b24af1
Edge coloring for the Commuting2qGateRouter (#8341)
* * Added an edge coloring to the Commuting2qGateRouter.

* * Black and lint.

* * Lint

* * ddt bug fix

* * docs

* * lint

* * Removed unneeded check.

* * Removed wrong test.

* * Updated docstring.

* * Test refactor

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-15 17:01:38 +00:00
Clemens Possel 3cc9c178be
Raise error for missing bounds in optimizer SNOBFIT (#8638)
* Update snobfit.py

Raise error for invalid `None`s in bounds of optimizer SNOBFIT

* Add SNOBFIT test for missing bounds

* Move refactored SNOBFIT test for missing bounds to test_optimizers_scikitquant.py

* Remove obsolete SNOBFIT import

* Add release note

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-14 20:07:18 +00:00
Naoki Kanazawa 69d2994779
Pulse reference mechanism (#8005)
* This commit add reference to schedule block and cleanup data structure of it with DAGSchedule class. Pulse builder call function is also updated to use reference mechanism. Now call function can be called without actual pulse program, which will be later assigned to the schedule through assign_reference method.

* Introduce ref_id instead of using (name, channels) tuple as a key of reference dict. Note that channels can be parametrized, and such dynamic key may break reference during programming. Even though if we update key with parameter assignment, assigned key doesn't work because they are different object, i.e. key is evaluated with "is" thus object id is important. Rather than introducing complicated mechanism to manage this, static ref key provides robust and cleaner solution.

* Add scope to reference manager

reference added to the program is managed with scope. this helps users to address parameters and reference to assign.

* fix parameter scope bug

* add more test

* documentation update

* support regex in get_parameters

* update reference manager implementation

Redefined ReferenceManager as a subclass of mutable mapping. This is the mapping to both schedule and channels.
Parameter management is excluded from the reference and moved to the schedule block.
All parameters including one in subroutines are exposed with .parameters property.

* wording edits

Co-authored-by: Daniel Egger <38065505+eggerdj@users.noreply.github.com>
Co-authored-by: Will Shanks <willshanks@us.ibm.com>

* add details of returned order

* fix bug in reference management

* update reference model

- reference take multiple keys instead of channels
- builder.refer command is newly added
- schedule.blocks returns reference replaced with actual subroutine if assigned
- remove dagschedule and revert to on the fly dag generation
- move reference to own file
- simplify reference manager
- update docs and tests

* add test for special parameter name

* docs update

Co-authored-by: Will Shanks <willshanks@us.ibm.com>
Co-authored-by: Daniel Egger <38065505+eggerdj@users.noreply.github.com>

* update delimiter

* misc updates

* update reference argument (name, **extra_keys)

* update builder command refer -> reference

* update parallel alignment dag generator to consider unassigned reference placed before undefined channels

* add search_parameters method

* cleanup

* reno

* documentation update

Co-authored-by: Will Shanks <willshanks@us.ibm.com>

* update parameter collection method not to merge parameter object in different scope.

* avoid overriding existing reference

* update comments about reference policy

* cleanup

* add comment about parent

* Update union of parameters, add some test for expression.

* Switch baseclass to UserDict

* Remove .name setter

* Update parameter logic. Turn scoped_parameters into a method.

* update _get_references logic

* Fix sequential dag generation logic

* add warning for parameter collision

* add test of sequential two edges
Co-authored-by: Will Shanks <willshanks@us.ibm.com>

* fix replace logic

* add explicit validate logic and cleanup constructor of instruction subclasses

* fix test

* add upgrade notice and API doc

* revert return type of parameters

* fix documentation

Co-authored-by: Daniel Egger <38065505+eggerdj@users.noreply.github.com>
Co-authored-by: Will Shanks <willshanks@us.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-14 16:09:06 +00:00
Pedro Rivero ae29802000
Add BaseResult functionality to primitives module (#8091)
* Add BaseResult functionality to primitives module

* Translate tests from pytest to unittest

* Update docstring

* Update __post_init__ docstring

* Add experiments property and update types

* Refactor variable names

* Refactor _field_values

* Finilize docstring

* Add renlease note

* Fix lint errors

* Fix lint docstring errors

* Fix formatting

* Fix variable names

* Remove BaseResult from primitives init and update test imports

* Rename BaseResult to BasePrimitiveResult

* Update qiskit/primitives/base_result.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Cache properties in base result since child dataclasses are frozen

* Revert "Cache properties in base result since child dataclasses are frozen"

This reverts commit 0d505a1cf1.

* Update experiments type, add decompose method, and validate data types

* Fix lint

* Fix BaseResult post_init docstring

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Index BasePrimitiveResult in primitives module __init__

* Add bytes case to TestBasePrimitiveResult

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Exclude bytes from possible field types in BasePrimitiveResult

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
2022-09-14 13:12:41 +00:00
dlasecki b35b18a90f
Time Evolution Framework with primitives. (#8681)
* Implemented observables_evaluator.py with primitives.

* Added evolvers problems and interfaces to time_evolvers package.

* Mostly updated trotter_qrte.py to use primitives.

* Added observables_evaluator.py that uses primitives.

* Added observables_evaluator.py that uses primitives.

* Updated trotter_qrte.py to use primitives.

* Updated imports

* Updated typehints and limited use of opflow.

* Updated typehints and limited use of opflow.

* Removed files out of scope for this PR.

* Added annotations import.

* Applied some CR comments.

* Added reno.

* Accepting Statevector.

* Added attributes docs.

* Add pending deprecation for evolvers

* Renamed classes and linked to algorithms init.

* fix docstring

* Improved reno.

* Code refactoring.

* Black fix.

* Applied CR comments.

* Add deprecation msg to evolvers package

Co-authored-by: Manoel Marques <Manoel.Marques@ibm.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
2022-09-13 21:16:35 +00:00
Jake Lishman bcec9a314c
Fix OpenQASM 3 built-ins with classical conditions (#8731)
The `.condition` attribute for `Instruction` instances corresponding to
OpenQASM 3 built-ins (such as `reset` and `measure`) would previously be
ignored.  This now correctly nests them inside a a branching statement
in the exporter, so the condition is preserved.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-13 17:18:45 +00:00
Shelly Garion 780099972c
Add CS, CSdg and CCZ gates to the CNOTDihedral class (#8673)
* add CS, CSdg and CCZ gates to the CNOTDihedral class

* add CS, CSdg and CCZ gates to the CNOTDihedral tests

* add release notes

* fix test following review

* move assert in tests

* handle CCZGate() in dihedral_circuits

* test CSGate(), CSdgGate(), CCZGate()

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-13 02:02:45 +00:00
Max Rossmannek e8001f5448
feat: support sum(LinearMixin) (#8722)
* feat: support sum(LinearMixin)

This enables the use of `sum(...)` for subclasses of the `LinearMixin`
class. It also adds the reflective operand dunder methods `__radd__` and
`__rsub__`.

* Add crossreferences to release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-09-09 13:00:50 +00:00
Luciano Bello 686ba343cd
deprecate qiskit.pulse.utils.deprecated_functionality in favor of qiskit.utils.deprecation.deprecate_function (#8696)
* deprecate deprecated_functionality

* pylint: disable=cyclic-import

* Add reno

* Include Terra version in deprecation notice

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-09-08 19:57:10 +00:00
Takashi Imamichi 18b38a9123
Add an error check for Sampler (#8678)
* add an error check for sampler

* update

* Update qiskit/primitives/base_sampler.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* remove a duplicate check

* update an error messgage

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2022-09-08 10:38:53 +00:00
Luciano Bello 94904fa00c
Remove deprecated pulse-builder contexts (#8697)
* Remove qiskit.pulse.builder.inline as deprecated in 0.18.0 (2021-07-13)

* remove imports

* remove test

* Remove qiskit.pulse.builder.pad as deprecated in 0.18.0 (2021-07-13)

* reno

* Reword removal note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-09-07 22:52:46 +00:00
a-matsuo 30899cf996
Include primitive's run_options (#8694)
* include primitive's run_options

* rename to get_local_run_options
2022-09-07 08:33:53 +00:00
Edwin Navarro bb5201184b
Move circuit drawer files to `qiskit.visualization.circuit` (#8306)
* Add graph and circuit dirs

* Move files to new folders

* Finishing transition to circuit and graph dirs

* Finish import changes

* Positioning files and setting init entries

* Final tweaks to compatibility and lint

* Reduce to circuit dir only

* Cleanup

* Add qcstyle stub for docs

* Merge main conflicts fix

* Lint

* Change test message

* Fix _directive change

* Fix op.condition reference

* Change to _utils and cleanup

* Lint

* Fix _trim and dag_drawer test

* Allow direct import of text, etc.

* Add comment explaining backwards-compatibility imports

* Add release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-09-07 01:12:00 +00:00
Ikko Hamamura 6927a8d26b
Default run_options for Primitives (#8513)
* Add run_options to Primitives

* rm unnecessary comments

* initial commit of Settings dataclass

* Revert "initial commit of Settings dataclass"

This reverts commit 96b8479fe4.

* fix lint, improve docs, don't return self

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-05 15:37:43 +00:00
a-matsuo b737fb5e64
Gradients with the primitives (#8528)
* added the gradients with the primitives

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* add run_options and supported gate

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* added unittests

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* lint

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* fix based on the comments

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* fix

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* add spsa gradient

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* simplify + async

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* added gradient variance

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* lint

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* added the run_options field

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* fix lint

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* fix based on comments

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* wip fix2

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* fix

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* lint

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* fix epsilon and doc

* lint

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* fix

* Update qiskit/algorithms/gradients/base_sampler_gradient.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update qiskit/algorithms/gradients/base_sampler_gradient.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update qiskit/algorithms/gradients/base_estimator_gradient.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update qiskit/algorithms/gradients/base_sampler_gradient.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update qiskit/algorithms/gradients/base_estimator_gradient.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update qiskit/algorithms/gradients/base_estimator_gradient.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* change epsilon error

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update qiskit/algorithms/gradients/estimator_gradient_result.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update qiskit/algorithms/gradients/sampler_gradient_result.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* add gradient test

* added batch size in spsa gradients

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* fix

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* lint

* Update qiskit/algorithms/gradients/lin_comb_estimator_gradient.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* add operator tests

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* consistent name

* rewrite spsa

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* use algorithm job

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Takashi Imamichi <imamichi@jp.ibm.com>
2022-09-05 14:05:35 +02:00
Edwin Navarro aca01eb986
Clean up text drawer compression issues (#8588)
* Add barrier labels to mpl and text drawers

* Release note

* Add import

* Lint

* Add barrier labels to latex drawer

* Remove utils changes

* Cleanup

* Fix merge conflict

* Lint

* Remove label property for barriers and snapshots and increase mpl label font size

* First steps

* Fix vert spacing with text between lines

* Fix low compress connections and change tests

* Add tests

* Additonal test

* Lint

* Add back test

* Release note

* Fix typo in release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-02 23:43:15 +00:00
ElePT 9ddc97da35
Fidelity interface using primitives (#8303)
* fidelity_poc

* init stuff

* simplified design

* unittests

* unittest working

* optional parameters

* typo

* documentation

* Update test/python/primitives/fidelity/test_fidelity.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update qiskit/primitives/fidelity/base_fidelity.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* black

* import order in test fixed

* docstring fixed

* Update qiskit/primitives/fidelity/base_fidelity.py

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* context removed

* Reset branch

* Add init

* Fix inits

* lint fixes

* removed abstractmethod label for set_circuits

* added support for setting only one circuit

* new unittest

* Move fidelities to algorithms

* Update interface with new design doc

* Fix docstrings and unit tests

* Add evaluate

* Adapt signature run

* Make job async

* Fix types

* Remove async, cache circuits

* Update evaluate method, replace use of np

* Remove circuits from init

* Add async, tests, update docstrings

* Add default run options

* change names, abstract methods, improve docstrings

* Update docstrings, typing

* Fix style

* Update qiskit/algorithms/fidelities/base_fidelity.py

Co-authored-by: Declan Millar <declan.millar@ibm.com>

* Update qiskit/algorithms/fidelities/base_fidelity.py

Co-authored-by: Declan Millar <declan.millar@ibm.com>

* Make async

* Add FidelityResult

* Update qiskit/algorithms/fidelities/__init__.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Add to algorithms init

* Rename classes

* Apply review comments

* Update preprocessing

* Update docstrings

* Move run to base class

* Remove left/right params

* Apply reviews steve/julien/hamamura

* Fix typo

* Style changes

* Allow different num.params in circuit 1 and 2

* Fix unittest typo

* Fix black

* Fix docs

* Fix style/docstrings

* Add AlgorithmJob

* Add truncate, fix result docstring

* Completely remove left-right

* Add comments

* Make create circuit public

* Remove empty param distinction

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* change list preprocessing

* Update qiskit/algorithms/algorithm_job.py

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Apply comments Steve

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update test/python/algorithms/state_fidelities/test_compute_uncompute.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Style changes

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Apply comments Julien

* Style fix

* Fix bug for lists of numpy values

* Support single circuits

* Support single circuits

* Add fidelity interface using primitives

* Apply reviews

* Fix docs

* Fix docs

* Fix docs

* Fix lint

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update qiskit/algorithms/state_fidelities/compute_uncompute.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update releasenotes/notes/add-fidelity-interface-primitives-dc543d079ecaa8dd.yaml

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update qiskit/algorithms/state_fidelities/__init__.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update qiskit/algorithms/state_fidelities/base_state_fidelity.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

Co-authored-by: Gian Gentinetta <gian.gentinetta@gmx.ch>
Co-authored-by: Gian Gentinetta <31244916+gentinettagian@users.noreply.github.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: dlasecki <dal@zurich.ibm.com>
Co-authored-by: Declan Millar <declan.millar@ibm.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-02 21:52:48 +00:00
Naoki Kanazawa ce1f8fedbb
Add curve fill control option to pulse drawer (#8658)
* Add fill control option

* reno

* add option description in docstring

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-02 04:34:24 +00:00
Matthew Treinish ab52d8b8bb
Add ResetAfterMeasureSimplification transpiler pass (#8330)
* Add ResetAfterMeasureSimplification transpiler pass

This commit adds a new transpiler pass to simplify resets after a
measurement. This pass when run will replace any reset after a
measurement with a conditional X gate. This is because the reset
operation on IBM backends is implemented by performing a conditional x
gate after a reset. So doing this simplification will improve the
fidelity of the circuit because we're removing a duplicate measurement
which was implicit in the reset. This pass is based on the marz library:
https://github.com/Qiskit-Partners/marz which did the same thing but at
the QuantumCircuit level.

One note is that this pass is basically specific to IBM backends so it's
not added to the preset pass managers. Ideally we'd be able to have the
IBM backends run this as part of the init stage or something to do the
logical transformation early in the compilation. But right now there is
no mechanism to do this (see #8329), so for now having the pass and
letting users specify it in the pass manager directly is the best
option. After #8329 is implemented we can look at adding this pass to
that hook interface in the ibm provider's backends directly so that they
can leverage this optimization whenever they're the compilation target.

* Fix lint

* Tweak wording on release note

* Remove stray debug draw() call

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-02 02:03:56 +00:00
Matthew Treinish 2ab0ae5112
Enable multiple parallel seed trials for SabreSwap (#8572)
* Enable multiple parallel seed trials for SabreSwap

The SabreSwap algorithm's output is quite linked to the random seed used
to run the algorithm. Typically to get the best result a user will run
the pass (or the full transpilation) multiple times with different seeds
and pick the best output to get a better result. Since #8388 the
SabreSwap pass has moved mostly the domain of Rust. This enables us to
leverage multithreading easily to run parallel sabre over multiple seeds
and pick the best result. This commit adds a new argument trials to the
SabreSwap pass which is used to specify the number of random seed trials
to run sabre with. Each trial will perform a complete run of the sabre
algorithm and compute the swaps necessary for the algorithm. Then the
result with the least number of swaps will be selected and used as the
swap mapping for the pass.

* Make parallel case fully deterministic

The parallel trial code was potentially non-deterministic in it's
execution because the way the parallel trials were compared was
dependent on execution speed of the pass. This could result in a
different output if results with equal number of swaps finished
executing in differing amounts of time between runs. This commit
addresses this by first collecting the results into an ordered Vec
first which is then iterated over serially to find the minimum swap
count. This will make the output independent of execution speed of the
individual trials.

* Fix test failures

This commit updates tests which started to fail because of the different
RNG behavior used by the parallel SabreSwap seed trials. For the most
part these are just mechanical changes that either changed the expected
layout with a fixed seed or updating a fixed seed so the output matches
the expected result. The one interesting case was the
TestTranspileLevelsSwap change which was caused by different swaps being
inserted that for optimization level enabled the 2q block optimization
passes to synthesize away the swap as part of its optimization. This was
fixed by changing the seed, but it was a different case than the other
failures.

* Add swap_trials argument to SabreLayout

This commit adds a swap_trials argument to the SabreLayout pass so that
users can control how many trials to run in SabreSwap internally. This
is necessary for reproducibility between systems for the same reason
it's required on SabreSwap.

* Add comment explaining the intermediate Vec usage

* Update layout in new test

* Update releasenotes/notes/multiple-parallel-rusty-sabres-32bc93f79ae48a1f.yaml

Co-authored-by: Kevin Hartman <kevin@hart.mn>

* Remove intermediate Vec for parallel trials

In an earlier commit we switched the parallel iterator to collect into
an intermediate `Vec` to ensure the output result was deterministic. The
min_by_key() will have a degree of non-determinism for equal entries as
the parallel iterator's threads finish. However, collecting to a Vec
isn't necessary as we can use the index as an element in a 2 element
array we can get the deterministic evaluation and avoid the overhead of
collecting into a `Vec`. This commit makes this change to improve the
performance of the parallel execution path.

Co-authored-by: Kevin Hartman <kevin@hart.mn>

Co-authored-by: Kevin Hartman <kevin@hart.mn>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-01 22:12:28 +00:00
Ikko Hamamura f1c5f5e272
Remove deprecated methods and arguments in quantum_info (#8510)
* Remove deprecated methods and arguments in quantum_info

* revert pauli.py

* add releasenote

* rm pauli_list argument

* update reno

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-01 14:34:58 +00:00
Luciano Bello 69ad6c66d5
Use np.array_split instead of np.split to support uneven splits in spsa._batch_evaluate (#8634)
* Use np.array_split instead of np.split to support uneven splits in spsa._batch_evaluate

* better testing

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update test/python/algorithms/optimizers/test_spsa.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* len of a boolean

* Apply suggestions from code review

* Fix Sphinx ref

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-31 22:04:17 +00:00
Manoel Marques 9195ec183f
Deprecate Algorithms Factorizers and Linear Solvers (#8617)
* Deprecate HHL and Shor

* Deprecate factorizers and linear solvers

* Fix docstrings
2022-08-31 13:42:09 +00:00
Anthony-Gandon 548dae2cb8
Implements two-step tapering (#8590)
* Adds two new methods for the tapering: `convert_clifford` and `taper_clifford`

* Adds two new methods for the tapering: `convert_clifford` and `taper_clifford`.
Adds a corresponding test.

* Make black

* Make lint

* Resolving the duplication and documenting the tapering.

* Add release note.

* Small changes

* Double the OpflowError + Update docstring indent

* Apply suggestions from code review

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-31 03:38:33 +00:00
Matthew Treinish cef0a8cc43
Add stage plugin interface for transpile (#8305)
* Add stage plugin interface for transpile

This commit adds a new plugin interface to qiskit for enabling external
packages to write plugins that will replace a stage in the transpilation
pipeline. For example, if an external package had a custom layout pass
that they wanted to integrate into transpile() they could export a
plugin using this new interface and then users would just need to run

transpile(.., layout_method=foo)

This adds long asked for extensibility to the transpiler so that to
cleanly integrate new transpiler passes we're no longer required to
merge the features into terra. This should hopefully make it easier for
downstream pass authors to integrate their passes into terra and make it
easier for the terra maintainers to evaluate new transpiler passes.

* Fix docs builds

* Fix doc warning

* Make routing methods all plugins

This commit converts all the built-in routing method options into
separate plugins and also adds a default plugin for the default behavior
at each optimization level. To support using plugins for routing method
adding the optimization_level to the passmanager config was necessary so
that the plugin has sufficient context on how to construct the routing
pass used for the routing stage. As depending on the optimization level
the settings for each pass differs. For example on stochastic swap the
number of stochastic trials increases for level 3 to try and find a
better solution at the cost of more runtime.

* Add plugin usage to level 3

* Add plugin support to level 0 preset pass manager

* Add default plugin to reserved routing methods list

* Add release notes

* Add tests

* Apply suggestions from code review

Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>

* Apply suggestions from code review

Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>

* Remove raise on non-builtin layout method argument

* Fix typo

* Deduplicate code in built-in routing plugins

This commit deduplicates the code in the built-in routing stage plugins.
First it removes the default plugin which was duplicated with the
stochastic and sabre plugins. There was no functional difference between
just setting the implicit default method name and using a per method
plugin and having a standalone default plugin. Secondly all the vf2 call
limit code is abstracted into a helper function which reduces code
duplication.

* Make vf2 call limit function private

* Deduplicate code in stochastic swap plugin

* Expand example plugin documentation to show more complete use case

* Update qiskit/transpiler/preset_passmanagers/level1.py

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* Add missing TODO comment

* Unify vf2 call limit handling

* Remove default plugin from entry points

* Simplify level 3 optimization stage logic

* Update qiskit/transpiler/preset_passmanagers/plugin.py

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* Prefer toqm plugin if one is available

The qiskit-toqm project will be one of the first users of this plugin
interface. Once this is released in qiskit, qiskit-toqm will likely
publish their own plugin soon after and if they do we want that plugin
to be used instead of the hardcoded stage in terra. This commit updates
the logic for toqm handling to only use the built-in toqm if a version
of qiskit-toqm is installed without a plugin present.

* Apply suggestions from code review

Co-authored-by: Kevin Hartman <kevin@hart.mn>
Co-authored-by: Toshinari Itoko <15028342+itoko@users.noreply.github.com>

* Fix lint

* Remove unnecessary elses in builtin plugins

* Apply suggestions from code review

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* Make optimization level a plugin argument

* Add test coverage for all built-in routing plugins

* Reorder stage variables to execution order

Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Kevin Hartman <kevin@hart.mn>
Co-authored-by: Toshinari Itoko <15028342+itoko@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-30 18:16:51 +00:00
Joseph McElroy d163e89cd0
Fix LaTeX drawer on split-filesystem systems (#8629)
* Update circuit_visualization.py

Corrects issue #8542

* Update circuit_visualization.py

* Add release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-08-29 16:54:15 +00:00
Marc Sanz Drudis 231961d6cf
Steppable Optimizer (#8170)
* All Changes so far

* Revert "All Changes so far"

This reverts commit 871f29ef54.

* All changes again

* tests

* Formated documentation Gradient Descent

* Reviewed Documentation

* Dealing with CALLBACK

* Fixing documentation

* Documentation

* Apply suggestions from code review

Co-authored-by: Daniel J. Egger <38065505+eggerdj@users.noreply.github.com>

* GD docs

* Fixed format of documentation

* Typo

* Imported files CMAES

* Testing

* Forgot to add nit to result

* Started stopping conditions

* Fixed comments

* Changes

* merge and black

* Fixed documentation

* IDK why docs is missing optimize

* make black

* Updated Documentation

* Updated Documentation

* Remove CMAES and merge

* Removed CMAES

* Learning Rate Class

* Lint

* RENO and unittests

* Removed attribute documentation

* Fixed variable name

* Added Learning Rate

* Fixed unittestt

* Fixes

* Apply suggestions from code review

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Fixing utils?

* lint

* Fixed Reno?

* Update releasenotes/notes/steppable-optimizers-9d9b48ba78bd58bb.yaml

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Apply suggestions from code review

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Fixed documentation typo

* Removed properties

* Apply suggestions from code review

Co-authored-by: Daniel J. Egger <38065505+eggerdj@users.noreply.github.com>

* Fixed comments

* Learning Rate init

* LearningRate init

* Update qiskit/algorithms/optimizers/utils/learning_rate.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* changes

* changes

* I can't fix the documentation

* Accidentaly merged with an other branch

* remains

Co-authored-by: Daniel J. Egger <38065505+eggerdj@users.noreply.github.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-29 14:18:20 +00:00
Emilio a511d99c1f
Add CS and CCZ gates (#8583)
* add cs and ccz gates

* add csdg gate

* add gates to equivalence library

* add release note

* fix equivalences

* commit review suggestions

* simplify definitions and add ctrl_state to inverse

* removed unused import
2022-08-29 09:55:24 +02:00
Julien Gacon c008008be2
Fix decomposition for a single qubit and clbit (#8614)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-25 14:54:48 +00:00
Anthony-Gandon d970c46b42
Fix VQD callback not being used (#8576)
* Added support for non-hermitian operators in AerPauliExpectation

Fixes #415

QEOM creates a dictionary of operators to evaluate on the groundstate.
When using the noisy simulators (qasm_simulator or aer_simulator), one
could either use PauliExpectation (with noise) or AerPauliExpectation
(without noise). PauliExpectation works with non-hermitian operators
but internal methods of AerPauliExpectation raised an Error.
This is a workaround to this limitation.
Note that using include_custom=True on qasm allows the VQE to use a
local AerPauliExpectation without using the "expectation" input.
This does not apply to QEOM and one should explicitly define the
"expectation" input of the VQE for it to apply globally.

* Added support for non-hermitian operators in AerPauliExpectation

Fixes #415

QEOM creates a dictionary of operators to evaluate on the groundstate.
When using the noisy simulators (qasm_simulator or aer_simulator), one
could either use PauliExpectation (with noise) or AerPauliExpectation
(without noise). PauliExpectation works with non-hermitian operators
but internal methods of AerPauliExpectation raised an Error.
This is a workaround to this limitation.
Note that using include_custom=True on qasm allows the VQE to use a
local AerPauliExpectation without using the "expectation" input.
This does not apply to QEOM and one should explicitly define the
"expectation" input of the VQE for it to apply globally.

* Add a test case for non-hermitian operators.

* Add a test case for non-hermitian operators.

* Add a test case for non-hermitian operators.

* Update test/python/opflow/test_aer_pauli_expectation.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update aer_pauli_expectation.py

Use a generator instead of list

* Update qiskit/opflow/expectations/aer_pauli_expectation.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update releasenotes/notes/add-support-non-hermitian-op-aerpauliexpectation-653d8e16de4eca07.yaml

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Add a test case for PauliOp

* Change the test cases from using ~StateFn() to using StateFn(, is_measurement=True)

* Fix the formatting

* Working point for QEOM

* Small changes + Release note

* Undesired change

* Undesired change

* Indentation error

* Parenthesis

* Minor changes in docstring

* Minor changes in docstring

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-24 20:29:33 +00:00
dlasecki e6e5ff6ac6
Variational Quantum Time Evolution algorithm. (#8152)
* Fixed requirements-dev.txt

* Fixed some pylint.

* Fixed some pylint.

* Update Documentation variational principles

* updates documentation

* minor documentation

* Added unit tests docs and some package docs.

* Code refactoring.

* Code refactoring.

* Code refactoring.

* Update qiskit/opflow/evolutions/pauli_trotter_evolution.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Renamed the main folder.

* Code refactoring.

* Update qiskit/algorithms/quantum_time_evolution/variational/calculators/evolution_grad_calculator.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Code refactoring.

* Update qiskit/algorithms/time_evolution/variational/error_calculators/gradient_errors/error_calculator.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Code refactoring.

* Lint fixes.

* Code refactoring.

* Code refactoring.

* Code refactoring.

* Code refactoring.

* Code refactoring, docs fixed.

* Code refactoring, docs fixed.

* Code refactoring and docs improved.

* Exposed optimizer tolerance as an argument.

* Exposed allowed imaginary part as an argument.

* Exposed allowed numerical instability as an argument.

* Code refactoring.

* Introduced evolution_result.py class.

* Minor bugfix.

* Integrated evolution result to VarQte algorithms.

* Code refactoring.

* Black formatting fix.

* Fixed signatures.

* Fixed random seed setup.

* Fixed too long lines.

* Deleted unnecessary files.

* Some fixes in test_gradients.py

* Copyright date updated.

* Refactored getting rid of flags.

* Updated unit tests after refactoring.

* Removed a duplicated argument.

* Implemented general Quantum Time Evolution Framework interfaces.

* Updated docs.

* Reno added.

* Improved reno.

* Code refactoring.

* Code refactoring.

* Typehints added.

* Made variational_principle.py stateless.

* Updated copyright years.

* Simplified var_qte.py class.

* Refactored var_qte_linear_solver.py

* Refactored abstract_ode_function_generator.py

* Refactored var_qte_linear_solver.py

* Refactored var_qte.py

* Code formatting.

* ODE solvers and optimizers as objects, not strings.

* Update qiskit/algorithms/time_evolution/evolution_base.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Code refactoring.

* Introduced evolution problem classes.

* Code refactoring.

* Apply suggestions from code review

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Added unit tests.

* Lint fixed.

* Code refactoring.

* Removed error_based_ode_function_generator.py for MVP.

* Code refactoring

* Code refactoring

* Code refactoring

* Code refactoring

* Code refactoring

* Code review changes.

* Removed gradient code for now.

* Evolving observable removed. Evaluating observables added.

* Improved naming.

* Improved folder structure; filled evolvers init file.

* Added Evolvers to algorithms init file.

* Fixed missing imports.

* Code refactoring

* Fixed cyclic imports.

* Extracted ListOrDict.

* Code refactoring.

* Code refactoring.

* Fixed release note.

* Fixed inheritance order.

* Code refactoring.

* Code refactoring.

* Fixed cyclic imports.

* Name fix.

* Updated the algorithm to the latest version of interfaces.

* Code refactoring.

* Adapted unit tests to evolution problem.

* Implemented aux_ops evaluation.

* Fixed position of quantum_instance.

* Added algorithms to algorithms init.

* Imports refactoring.

* Imports refactoring.

* Updated code to the latest gradient framework.

* Code refactoring.

* Imports refactoring.

* Added gradient files.

* Code review addressed. Fixed tests.

* Switched to 1 sampler.

* Added unit tests for expected errors.

* Improved docs.

* Changed folder structure.

* Added test_evolution_grad_calculator.py unit test with bases.

* Updated interfaces.

* Added VarQite unit test with aux ops.

* Added VarQite unit test with aux ops.

* Added VarQrte unit test with aux ops.

* Update releasenotes/notes/add-variational-quantum-time-evolution-112ffeaf62782fea.yaml

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Code refactoring.

* Code refactoring.

* Code refactoring.

* Improved docs of variational principles.

* Code refactoring.

* Code refactoring.

* Simplified var principles folder structure.

* Opened VarQte algorithms for field modification.

* Improved Sphinx docs.

* Code refactoring.

* Introduced ode_function_factory.py

* Removed hardcoded rcond.

* Renamed hamiltonian_value_dict.

* Renamed hamiltonian_value_dict.

* Extracted lengthy expected results in tests.

* Updated unit tests.

* Apply suggestions from code review

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Apply suggestions from code review

* Extended release notes.

* Removed dead code.

* Improved ode solver types.

* Moved evolve method for now.

* Shortened Var Principles names.

* Updated metric_tensor_calculator.py

* Updated docs

* Removed ordered_parameters.

* Added and corrected code examples.

* Extended unit tests.

* Extended unit tests.

* Extended unit tests.

* Improved init files.

* Improved init files.

* Improved init files.

* Improved init files.

* Improved docs.

* Import fix

* Renamed sle to lse.

* Code refactoring.

* Replaced metric tensor calculator.

* Replaced evolution gradient calculator.

* Code refactoring.

* Removed evolution_grad_calculator.py

* Removed evolution_grad_calculator.py

* Evolution grad calculator removal; code refactoring; dirty bug fix.

* Added docs.

* Code refactoring

* Improved performance of evolution grad.

* Improved performance of evolution grad, code refactoring; bug fixed.

* Improved LSE solver handling.

* Improved docs.

* Unindented reno

* Mitigated some cyclic imports.

* Unindented reno

* Improved docs

* Lint resolutions

* Fix some line-too-long in tests

* Fixed lint.

* Fixed lint.

* Apply suggestions from code review

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Code review changes.

* Added reno for a bug fix.

* Fixed lint.

* Updated docs.

* Moved lse_solver to ODE factory.

* Made ODE factory optional and defaults set.

* Added expectation method argument and set defaults to PauliExpectation.

* Limited supported methods for real_time_dependent_principle.py.

* Fix imports.

* Updated docs.

* Implemented the Forward Euler ODE solver. Implemented a unit test.

* Set Forward Euler ODE solver as a default. Updated unit tests.

* Sync with main.

* Exposed ODE number of steps.

* Code refactoring

* Code refactoring

* Code refactoring

* Exposed ode_num_t_steps to the user; reduced default ode_num_t_steps; added ForwardEulerSolver to docs.

* Updated tests.

* Fixed CI.

* Fixed docs.

* Hides OdeFunction from the user.

* Update qiskit/algorithms/evolvers/variational/var_qrte.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update releasenotes/notes/add-variational-quantum-time-evolution-112ffeaf62782fea.yaml

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Removes unsupported error-based method flag for now.

* Switched num time steps to deltas in ODEs.

* Code refactoring.

* Fixed typhint.

* Switched back to num_steps for ODE.

* Slow tests and code refactoring.

* Code refactoring.

* Removed TD variational principle.

* Apply suggestions from code review

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Code refactoring.

* Improved signatures; support for list of parameter values.

* Code refactoring.

* Improved variable name.

* Updated docs.

Co-authored-by: CZ <ouf@zurich.ibm.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: woodsp-ibm <woodsp@us.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-23 15:55:07 +00:00
Naoki Kanazawa 3f9edfc83e
Add logic to return channels to FakeBackendV2 (#8444)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-22 22:35:42 +00:00
Edwin Navarro 93e2fc52f9
Add barrier labels and display in 3 circuit drawers (#8440)
* Add barrier labels to mpl and text drawers

* Release note

* Add import

* Lint

* Add barrier labels to latex drawer

* Remove utils changes

* Cleanup

* Fix merge conflict

* Lint

* Remove label property for barriers and snapshots and increase mpl label font size

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-19 15:49:15 +00:00
Jake Lishman 26ba58ad54
Fix QuantumCircuit.compose within control-flow scopes (#8570)
* Fix QuantumCircuit.compose within control-flow scopes

Previously, `QuantumCircuit.compose` with `inplace=True` would insert
the appended instructions outside the scope due to unchecked use of
`QuantumCircuit._append` (and direct modification of the `data`
attribute).  This now respects any active control-flow scopes.

Using `front=True` in conjunction with `inplace=True` within a
control-flow scope has no clear meaning, and so the behaviour is
forbidden.  Emitting a new circuit (`inplace=False`) while in an active
scope would produce a broken circuit - the active scope would need to be
cloned to ensure equivalence, but it wouldn't be part of any
Python-managed context, so the scope could never be closed.

* Finish writing documentation sentence

* Add missing docstring in test

* Add missing Sphinx directive

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-18 13:55:39 +00:00
Jake Lishman a0964c10aa
Fix QPY serialisation of ControlledGate with open controls (#8571)
* Fix QPY serialisation of ControlledGate with open controls

Previously, an incorrect definition and name would be re-instated on
QPY deserialisation of a `ControlledGate` instance with open controls.
The base name would include the dynamic `_o{ctrl_state}` suffix, causing
the suffix to later be duplicated, and the definition would duplicate
the logic that added the open controls.  This fixes both by stripping
the suffix on re-read before it is assigned, and serialising only the
"11...1" state definition, since this is what is required and stored by
`ControlledGate`.

* Add QPY backwards compatibility test

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-18 12:34:08 +00:00
Emilio 4fac3f4bea
accept single qubit in initialize to fix #8408 (#8463)
* accept single qubit in initialize

* only call conversion when not iterable

* add single Qubit to if statement

* add test

* fix imports

* modify docs; add release note

* accept single qubit in state preparation

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-16 16:07:13 +00:00
Israel F. Araujo 82c85d859b
Fix global phase in inverse of UCGate (#8508)
* Defines the inverse of the global phase

The inverse of UCGate is defined by simply inverting the existing decomposition, but the inverse of the global phase was missing.

* Tests the UCGate.inverse() function

* Lint

* Seed for building the matrices

* Replace `unitary_simulator` by using `qiskit.quantum_info.Operator`.

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Import `Operator` class

* Release notes

* Lint

* Test the phase of isometry decomposition

* Removes the `prelude` from the release notes file

* Replaces `matrix_equal` with `np.allclose`

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2022-08-14 17:37:03 +02:00
Alexander Ivrii 19fdd32aff
Adding Cliffords to QuantumCircuits as Operations (#7966)
* Adding Clifford to a QuantumCircuit natively; adding some tests; adding a preliminary Clifford optimization pass

* Making Instruction.condition into a property

* improving tests

* adding release notes

* A few changes based on review

* Removing definition from Operation interface. Instead adding
HighLevelSynthesis transpiler pass, and incorporating it into the preset
pass managers

* minor lint fix

* moving all of broadcast functionality to a separate file; removing broadcast from Operation interface and in particular from Clifford

* moving HighLevelSynthesis pass from Decompose to QuantumCircuit.decompose; slightly changing Decompose pass to skip nodes with definition attribute

* Fixing broadcasting for Cliffords

* making sure that transpile decomposes cliffords

* lint

* As per code review, replacing x._direction by getattr(x, '_direction', False)

* Removing condition from Operation API.

Removing previously added getter and setter to instruction.py.

As per code review, starting to replace condition getters and setters.
For now, only dagcircuit and circuit_to_instruction.

* pass over condition in transpiler code

* more refactoring of condition

* finishing condition pass

* minor fixes

* adding OptimizeClifford pass to __init__

* Improving release notes

* considering DAG nodes in topological order; adding a simple test to see this

* typo

* release notes fixes

* Adding TODO comment to HighLevelSynthesis pass

* another attempt to fix docs build

* Fix based on code review

* Only construction Operator from Instruction (as before) and from Clifford (for backward compatibility)
2022-08-10 19:41:43 +00:00
Ikko Hamamura dadacb8050
Improve the performance of taper in opflow (#8410)
* reduce

* add releasenote

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-10 15:09:00 +00:00
Alexander Ivrii f48aab2b01
Refactoring commutativity analysis and a new commutative inverse cancellation transpiler pass (#8184)
* experimenting with transpiler passes

* removing some prints

* minor cleanup

* Improving external test file

* Simplified commutative inverse cancellation pass

* black

* Removing duplicate code from CommutationAnalysis and DagDependency

* black and lint

* commutation_checker cleanup

* Adding tests for CommutativeInverseCancellation pass

The tests are adapted from CommutativeCancellation, InverseCancellation
and issue 8020.

* Removing external test python file

* Update qiskit/transpiler/passes/optimization/commutative_inverse_cancellation.py

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Update qiskit/transpiler/passes/optimization/commutative_inverse_cancellation.py

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Removing the use of dag node classes and taking args and op separately

* Removing runtime import

* removing unnecessary pylint-disable

* moving commutation_checker to qiskit.circuit and improving imports

* Adding commutative_checker tests

* running black

* linting

* Adding corner-cases to test_commutative_inverse_cancellation

* release notes

* black

* release notes tweaks

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-10 13:58:15 +00:00
Ikko Hamamura db612922aa
Add run method to primitives (#8382)
* add submit method

* add method docstrings

* deprecate context manager

* [new feature] append

* deprecate __call__

* optional in constructor

* Introduce PrimitiveFuture

* refactoring

* ping Sphinx<5.1

* Extend Job

* JobV1

* rename submit to run

* rm PrimitiveFuture

* fix lint

* add tests

* add releasenote

* rm _submit and add _run

* use dict for ids

* run cannot take integer indices

* deprecate args in constructor

* refactoring

* Update qiskit/providers/job.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update qiskit/primitives/base_sampler.py

Co-authored-by: Jessie Yu <jessieyu@us.ibm.com>

* refactoring

* support parameters in run

* fix docs (args order)

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: Jessie Yu <jessieyu@us.ibm.com>
2022-08-09 08:33:31 +00:00
Jun Doi 6a5adf20e8
Changing aer_simulator_statevector checking method (#8411)
* checking backend name by checking string is included

* added release note
2022-08-08 19:26:25 +00:00
Julien Gacon 2bab09c1aa
Fix ``ParameterExpression.is_real`` if ``symengine`` is installed (#8456)
* Fix is_real on ParameterExpression

* typo in reno

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-04 22:50:36 +00:00
Julien Gacon 37057987f4
Projected Variational Quantum Dynamics (#8304)
* pvqd dradt

* update as theta + difference

* black

* refactor test

* update to new time evo framework

* add gradients

* use gradient only if supported

* polishing!

- reno
- remove old pvqd file
- allow attributes to be None
- more tests

* fix algorithms import

* changes from code review

* add more tests for  different ops

* refactor PVQD to multiple files

* remove todo

* comments from review

* rm OrderedDict from unitary

no idea why this unused import existed, that should be caught before this PR?

* changes from code review

* remove function to attach intial states

* include comments from review

- support MatrixOp
- default for timestep
- update reno with refs
- test step and get_loss

* make only quantum instance and optimizer optional, and use num_timesteps

* fix docs

* add comment why Optimizer is optional

* use class attributes to document mutable attrs

* rm duplicate quantum_instance doc

* fix attributes docs

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-08-04 21:43:51 +00:00
Shelly Garion 82245c0141
Add optimization for TwoLocal synthesis when entanglement='full' (#8335)
* add optimization for CX subcircuits with full entanglement

* preserve the option of full_explicit

* add a test that full and full_explicit are the same

* add docstring to the test

* minor lint fix

* add comments following review

* minor fix: add default value None to entanglement_gates

* minor lint fix

* add the option reverse_linear, and remove full_entanglement

* add optimization for CX subcircuits with full entanglement

* preserve the option of full_explicit

* minor lint fix

* add comments following review

* add the option reverse_linear, and remove full_entanglement

* return extra space lines

* update comment

* add documentation in TwoLocal

* update documentation in TwoLocal

* add documentation in RealAmplitudes. Change default eantanglement to reverse_linear

* fix block size in reverse_linear

* enhance tests for reverse_local

* add documentation in EfficientSU2. Change default entanglement to reverse_linear

* reduce the nuber of tests of reverse_linear vs. full

* add a test that ZZ feature map works with reverse_linear entanglement

* style update

* add release notes

* add entanglement='pairwise' to the docs of TwoLocal

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
2022-08-02 16:32:40 +00:00
Edwin Navarro 244fd840a8
Fix MPL and LaTeX circuit drawer when `idle_wires=False` and there are barriers (#8321)
* Fix idle_wires False with barrier

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2022-07-28 23:37:43 +02:00
Julien Gacon 625ff98f68
Fix converting VectorStateFn to a CircuitStateFn (#8405) 2022-07-27 17:19:44 +00:00
Polly Shaw 28802cf057
Fixes #7078: Change prefix of MemorySlot channel in Qasm Instructions (#8166)
* Fixes #7078: Add is_schedulable property to qiskit.pulse.Channel and don't apply a delay to it if True

RegisterSlot and MemorySlot have this set to False. The default implementation in Channel sets it to True.

* Fixes #7078: Introduce ClassicalIOChannel as a subclass of pulse.Channel

RegisterSlot, MemorySlot and SnapshotChannel now derive from this class. There are some tests to fix.

* Fixes #7078: Make Acquire.channels only return the channel

* Fixes #7078: Execute black

* Fixes #7078: Put slots in new tuple in acquire

* Fixes #7078: Add is_schedulable property to qiskit.pulse.Channel and don't apply a delay to it if True

RegisterSlot and MemorySlot have this set to False. The default implementation in Channel sets it to True.

* Fixes #7078: Remove is_schedulable property from qiskit.pulse.channel

* Fixes #7078: Put checks in SetPhase, ShiftPhase and SetPhase. Remove check from Delay.

* Fixes #7078: Add unit tests for restrictions on Classical IO channels

* Fixes #7078: Add unit tests for abstract nature of ClassicalIOChannel

* Fixes #7078: Tidying after self-review.

* Fixes #7078: Add release note.

* Fixes #7078: remove typo

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2022-07-27 01:57:56 +00:00
Matthew Treinish f8681295dd
Fix handling of numpy arrays for indices in marginal_distribution (#8288)
* Fix handling of numpy arrays for indices in marginal_distribution

This commit fixes an issue with the marginal_distribution() function
where it would previously error if a numpy arrray of ints was passed in
for the indices parameter. This was caused by the input validation
looking for empty input by checking `not indices` which isn't valid for
numpy arrays. This commit fixes this by adjusting the check for
empty lists to work with any sequence input.

Fixes #8283

* Update releasenotes/notes/fix-numpy-indices-marginal-dist-45889e49ba337d84.yaml

Co-authored-by: Jim Garrison <jim@garrison.cc>

Co-authored-by: Jim Garrison <jim@garrison.cc>
2022-07-25 15:12:46 +00:00
Julien Gacon 1312624309
Fix `EvolvedOp.to_instruction` (#8384)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-21 08:38:55 +00:00
Julien Gacon d9af1d1f7a
Fix `Optimizer` reconstruction from `settings` (#8381)
* fix settings in optimizers

* add reno

* don't duplicate args

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-20 19:26:39 +00:00
Adenilton Silva f2c2fe263e
Fix Uc gate global phase (#8231)
* global phase UCGate

* Create global-phase-ucgate-cd61355e314a3e64.yaml

* Update qiskit/extensions/quantum_initializer/isometry.py

* Update qiskit/extensions/quantum_initializer/isometry.py

Co-authored-by: ewinston <ewinston@us.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-19 18:41:06 +00:00
Kevin J. Sung 77535607f9
Fix bug in circuit decompose (#8364)
* fix bug in circuit decompose

* add test

* Update test/python/circuit/test_circuit_operations.py

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-19 17:36:36 +00:00
Matthew Treinish 6dd0d69ec9
Reimplement SabreSwap heuristic scoring in Rust (#7977)
* Reimplement SabreSwap heuristic scoring in multithreaded Rust

This commit re-implements the core heuristic scoring of swap candidates
in the SabreSwap pass as a multithread Rust routine. The heuristic
scoring in sabre previously looped over all potential swap candidates
serially in Python and applied a computed a heuristic score on which to
candidate to pick. This can easily be done in parallel as there is no
data dependency between scoring the different candidates. By performing
this in Rust not only is the scoring operation done more quickly for
each candidate but we can also leverage multithreading to do this
efficiently in parallel.

* Make sabre_swap a separate Rust module

This commit moves the sabre specific code into a separate rust module.
We already were using a separate Python module for the sabre code this
just mirrors that in the rust code for better organization.

* Fix lint

* Remove unnecessary parallel iteration

This commit removes an unecessary parallel iterator over the swap scores
to find the minimum and just does it serially. The threading overhead
for the parallel iterator is unecessary as it is fairly quick.

* Revert change to DECAY_RESET_INTERVAL behavior

* Avoid Bit._index

* Add __str__ definition for DEBUG logs

* Cleanup greedy swap path

* Preserve insertion order in SwapScores

The use of an inner hashmap meant the swap candidates were being
evaluated in a different order based on the hash seeding instead of the
order generated from the python side. This commit fixes by switching the
internal type to an IndexMap which for a little overhead preserves the
insertion order on iteration.

* Work with virtual indices win obtain swap

* Simplify decay reset() method

* Fix lint

* Fix typo

* Rename nlayout methods

* Update docstrings for SwapScores type

* Use correct swap method for _undo_operations()

* Fix rebase error

* Revert test change

* Reverse if condition in lookahead cost

* Fix missing len division on lookahead cost

* Remove unused EXTENDED_SET_WEIGHT python global

* Switch to serial iterator for heuristic scoring

While the heuristic scoring can be done in parallel as there is no data
dependency between computing the score for candidates the overhead of
dealing with multithreading eliminates and benefits from parallel
execution. This is because the relative computation is fairly quick and
the number of candidates is never very large (since coupling maps are
typically sparsely connected). This commit switches to a serial iterator
which will speed up execution in practice over running the iteration in
parallel.

* Return a 2d numpy array for best swaps and avoid conversion cost

* Migrate obtain_swaps to rust

This commit simplifies the rust loop by avoiding the need to have a
mutable shared swap scores between rust and python. Instead the obtain
swaps function to get the swap candidates for each layer is migrated to
rust using a new neighbors table which is computed once per sabre class.
This moves the iteration from obtain swaps to rust and eliminates it as
a bottleneck.

* Remove unused SwapScores class

* Fix module metadata path

* Add release note

* Add rust docstrings

* Pre-allocate candidate_swaps

* Double swap instead of clone

* Remove unnecessary list comprehensions

* Move random choice into rust

After rewriting the heuristic scoring in rust the biggest bottleneck in
the function (outside of computing the extended set and applying gates
to the dag) was performing the random choice between the best candidates
via numpy. This wasn't necessary since we can just do the random choice
in rust and have it return the best candidate. This commit adds a new
class to represent a shared rng that is reused on each scoring call and
changes sabre_score_heuristic to return the best swap.

The tradeoff with this PR is that it changes the seeding so when
compared to previous versions of SabreSwap different results will be
returned with the same seed value.

* Use int32 for max default rng seed for windows compat

* Fix bounds check on custom sequence type's __getitem__

Co-authored-by: Kevin Hartman <kevin@hart.mn>

* Only run parallel sort if not in a parallel context

This commit updates the sort step in the sabre algorithm to only run a
parallel sort if we're not already in a parallel context. This is to
prevent a potential over dispatch of work if we're trying to use
multiple threads from multiple processes. At the same time the sort
algorithm used is switched to the unstable variant because a stable sort
isn't necessary for this application and an unstable sort has less
overhead.

Co-authored-by: Kevin Hartman <kevin@hart.mn>
2022-07-19 15:34:38 +00:00
Daniel J. Egger 40668f04b5
Tensored fitter (#8345)
* This PR adds a method subset_fitter to the TensoredMeasFitter in Terra. The 
subset_fitter provides a new fitter by reordering the calibration matrices in the internal 
list of the fitter.
2022-07-15 21:21:56 +02:00
Julien Gacon 38d1ef8293
Fix pairwise entanglement (#8346) 2022-07-15 12:42:27 +00:00
Prakhar Bhatnagar 56501cc673
Switched to `StandardScaler` from deprecated `normalize` in `NaturalGradient` (#8299)
* switched to `StandardScaler`

* Don't mention private methods in reno

* Fix typo

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-13 18:18:23 +00:00
Edwin Navarro 81abc384e4
Add wire_order option to all circuit drawers to allow defining the order of the wires (#8173)
* Add wire_order option - all except conditions working

* Update gate_span

* mpl drawer working with wire_order and reverse_bits

* Fix latex conditions for any wire order

* Adding text change

* Complete text drawer changes

* Lint and reno

* Lint

* More lint

* Fix typos

* Testing, deprecations, typos

* Lint

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-12 17:11:16 +00:00
Matthew Treinish bb4d52a290
Move release note in wrong location and add script to block this (#8320)
* Move release note in wrong location and add script to block this

In #8201 I added a release note as part of the PR which documented the
change in behavior. However, I accidentally committed this file in the
wrong location (by running reno new outside of the repo root). This
meant the file was never actually included in the release notes for the
0.21.0 release. This commit corrects this oversight and moves it back to
the proper location.

However, since this isn't my first time making this mistake and I can
expect that others will make it too in the future. This commit also adds
a new script to detect this and raise an error when release notes are
present outside of the proper location. By running this as part of lint
jobs we'll block this mistake from happening again.

* Fix lint

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-12 12:16:03 +00:00
kUmezawa 925d8cbf4d
Added argsort and sort method to SparsePauliOp (#8016)
* first share

* Remove reverse option

* Apply Lint

* Modify wording

* add release note

* Correct the text

* Correct the text

* Delete words

* Added description of arguments

* Fix typos & update reno

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2022-07-12 10:35:56 +00:00
Naoki Kanazawa d50d99a50c
fix limit_amplitude bug (#8308) 2022-07-07 13:02:22 +00:00
Kevin J. Sung c60d3b8e73
add atol parameter to SparsePauliOp.equiv (#8281)
* add atol parameter to SparsePauliOp.equiv

* lint

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-05 16:27:05 +00:00
Naoki Kanazawa 36c91add58
Avoid direct-CXs in RZX calibration pass (#8276)
* Step1. Add handling for direct CX in RZX calibration builder. PulseError is replaced with User warning not to crash pass manager execution.

* Step2. Cleanup RZX builder. Unreachable errors are removed. Use inplace mode for schedule construction to avoid redundant deep copy. Deprecate unused argument.

* Step3. Reorganize calibration module structure. Usually, in the transpile pass modules, single file contains a single (or similar) pass. RZX builder passes are moved to rzx_builder, Pulse gate pass is moved to pulse_gate and base class is moved to base_builder

* Step4. Write release note

* docs update and turn a cal validation into a separate function. calibration type enum is added for user-friendly error message.

Co-authored-by: Thomas Alexander <talexander@ibm.com>

Co-authored-by: Thomas Alexander <talexander@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-04 16:32:27 +00:00
Julien Gacon c796e71e32
Fix ``maxfun`` default in ``L_BFGS`` (#8285)
* Fix maxfun and rm deprecated arg

* update docs, rm "epsilon"

* add reno

* lint

* update reno
2022-07-04 08:57:07 +00:00
Luciano Bello 0ab9e1e148
Argument `epsilon` and `factr` of optimizers `L_BFGS_B` and `factr` of `P_BFGS` has been removed (#8210)
* Remove L_BFGS_B and P_BFGS deprecated arguments

* date

* reno

* Update releasenotes/notes/remove_optimizers_L_BFGS_B_epsilon-03f997aff50c394c.yaml

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-01 13:22:09 +00:00
aeddins-ibm 64bf148bec
Speed up pauli evolve clifford (#8199)
* Vectorize base_pauli._evolve_clifford

Per issue #8177 . Seems to give a ~100x speed up by vectorizing for loops.

I am not sure about the memory cost of the vectorization (einsum, etc).

* support Pauli.evolve in addition to PauliList.evolve

- use ._x instead of .x to get correct array dimensionality
- use 'uint8' dtype for phases (not doing so raised error for Pauli but not for PauliList)

* Simpler evolve computation

Revised the evolve computation to be more like the original nested-for code before this PR, but replacing one of the two for-loops with PauliList operations. In earlier commits in this PR, I tried to avoid both for-loops using einsum, but that seemed to have worse scaling with number of qubits.

Some clever way to eliminate the remaining for loop could be nice, but at least this code speed seems comparable to or better than the old for-loop code in speed for all cases. Avoiding introducing a scaling problem at higher qubit number seems important since that's what users might want Cliffords for in the first place.

* formatting (black)

* change x to _x

compatibility with BasePauli class

* fix rare error for evolving a Pauli

- preceding commit in this PR changed an `x` to `_x` to keep linter happy, but this introduced a rare bug when evolving Pauli type (but not PauliList AFAICT).
- made less ambiguous test using `isinstance` to avoid this bug

* avoid calling isinstance()

- avoid calling istinstance(self, PauliList) inside the evolve method of BasePauli, since that is problematic.
- the replacement has an extra call to np.sum, but this does not seem to significantly impact overall time of execution.

* add release note

* Reword release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-28 18:21:22 +00:00
Paul Nation 1082240493
Combine circuits with clbits onto those with none (#7823)
* Combine circuits with clbits onto those with none

* add tests

* fix reg adding

* run black

* Take into account that other might not be a QC

* add additional multireg test

* fix reimport

* black

* Fix for registerless bits

* Add feature release note

* black again

* Simplify code

* Reword release note

* Make tests less dependent on hardcoded names

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-06-28 01:01:15 +00:00
Ikko Hamamura a5d71d7739
Add shots option to primitives (#8137)
* add shots option

* Apply suggestions from code review

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* add test_with_shots_option_none to Sampler

* rename seed_primitive to seed

* Update qiskit/primitives/estimator.py

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-27 21:20:22 +00:00
Jake Lishman 8d5e3ca676
Fix UnitaryGate.qasm() with unused qubits (#8234)
The OpenQASM 2 exporter has a special case for providing `gate`
definitions, which was implemented purely for `UnitaryGate`.  This is
stateful per instruction, and does not generally behave well with the
rest of the exporter.  This commit fixes one misbehaviour: the way the
qubit operands for the definition was calculated was unreliable in both
order and number of qubits, if any of the qubits were unaffected by
the gate operation.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-24 19:20:02 +00:00
Luciano Bello f3877a2983
Deprecated `QiskitIndexError` removed (#8209)
* QiskitIndexError removed

* date

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-23 22:37:43 +00:00
Matthew Treinish 57540c1697
Bump version strings post pre-release (#8228)
* Bump version strings post pre-release

Now that qiskit-terra 0.21.0rc0 is out the door we should bump the version
string on main to show the source version we're installing is newer
than what's been pre-released.

* Move 0.21 release notes into a separate directory

* Update cargo.toml too
2022-06-23 17:16:28 -04:00
Jake Lishman f51dd9cb87
Release notes for Terra 0.21rc1 (#8227)
* Fix typos in release notes

* Remove release notes from 0.20.x patches

* Update releasenotes/notes/delay-fake-backends-3f68c074e85d531f.yaml

* Update add_check_from_sparse_list-97f13fde87c7bcb6.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2022-06-23 19:01:05 +00:00
Vishnu Ajith a5b5f81fce
Adding variational Quantum Deflation Algorithm for computing higher energy states (#7747)
* initial commit

* initial commits

* changed init, get_enegery_value and compute_eigenvalue

* working kstatevqe

* bug fixing

* fixing overlap term

* fixed kstatevqe

* fixed bounds, gradient and aux_ops in kstatevqe.py

* changing kstatevqe to vqd

* changing filename and bug fixes

* adding tests for vqd

* mirroring changes in deprecated methods

* style check and linting

* modifying doc string

* adding release notes

* lint fixing releasenote and vqe.py

* lint fixes

* added warning and formatted

* test fix

* Update qiskit/algorithms/eigen_solvers/vqd.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update qiskit/algorithms/eigen_solvers/vqd.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update qiskit/algorithms/eigen_solvers/vqd.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update qiskit/algorithms/eigen_solvers/vqd.py

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* Update qiskit/algorithms/eigen_solvers/vqd.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* docstring fixes

* modified to use eval_observables and allow the use of any optimiser

* lint fixes and fixing OPTIMIZER import

* Apply suggestions from code review: grammatical fixes in docs and docstrings

Co-authored-by: dlasecki <dal@zurich.ibm.com>

* fixing minimizer class

* fixed release note, pylint, tox and resolved comments

* fixing lint, minimizer and docstring ordering

* lint fix

* lint fixes and release note fix

* test, lint, releasenote fixes

* removed dprecated optimizer and related fixes

* modifying optimizer.minimize

* modifying get_energy_evaluate typehints and docstring

Co-authored-by: Pauline Ollitrault <pauline.ollitrault1@gmail.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: dlasecki <dal@zurich.ibm.com>
2022-06-23 17:25:54 +00:00
Vicente P. Soloviev 5c51d3a1ce
UMDA optimizer added (#8084)
* UMDA optimizer added

* requirements update

* tests

* tests

* remove pandas

* documentation and tests

* pylint doc fix

* update lint

* lint test OK

* little fix

* private attributes, getters and setters

* private attributes, getters and setters

* UMDA extends Optimizer

* new example without dependencies

* tests update

* pylint converage

* pylint converage

* pylint converage

* reviewer suggestions

* tox

* tests

* tests

* documentation

* Update qiskit/algorithms/optimizers/umda.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update qiskit/algorithms/optimizers/umda.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Update qiskit/algorithms/optimizers/umda.py

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* release note, and reviewer notes

* tox

* tests

* tests

* remove some getter/setter

* review

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-23 12:36:32 +00:00
Daiki Murata 8455c9f459
Remove deprecated classes and methods in quantum_info (#8070)
* remove deprecated

* fix test

* fix test

* fix cyclic dependency

* create releasenote

* leave import path

* fix lint

* deprecate argument

* Update qiskit/quantum_info/operators/symplectic/pauli.py

* Remove already-expired deprecation

* Revert unnecessary over-specific import

* Flesh out detail in release note

* Issue deprecation warning for old Pauli path

* Reinstate buggy deprecated behaviour

* Reinstate None default for Pauli data kwarg

Co-authored-by: ikkoham <ikkoham@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-23 11:16:16 +00:00
Junye Huang 3241978340
Move `qiskit.test.mock` to `qiskit.providers.fake_provider` and deprecate (#8121)
* redirect imports from qiskit.test.mock to qiskit.providers.fake_provider

* import the rest of classes in fake_backend_v2 to fake_provider

* redirect imports to fake_provider

Anything that can be imported from fake_provider root are imported from there instead of sub files.

* change jupyter-execute to code-block

* redirect import

* Combine multiple imports into one

* Add missing )

* move all files except __init__ from qiskit.test.mock to qiskit.providers.fake_provider

* redirect imports in fake_provider.__init__.py

* redirect imports in mock.__init__.py

* Use relative imports in fake_provider.__init__.py

* redirect .utlis imports

* Don't import fake_backend_v2.py in __init__ to avoid clashes of FakeBackendV2 names

* Match imports from the old and new __init__

* Organize imports

* black linting

* Fix FakePulseBackend import order dependency

* fix cyclic import

* move relative import after absolute import

* fix cyclic import

* Update MANIFEST.ini with new path

* add deprecation warning

* add deprecation test

* add release note

* move test files from test.python.mock to test.python.providers.fake_provider

* linting

* linting

* change deprecation warning location

* update path for tools/update_fake_backends.py

* rename docstrings

* Update ibmq_mock.py

* import back FakeBackendV2 and FakeBackend5QV2 in __init__

* Modify release note

* reformat release note

* remove unnecessary tests

These two tests were introduced in PR #7437 to test the new imports which are not needed any more: https://github.com/Qiskit/qiskit-terra/pull/7437#discussion_r810843786

* Use relative imports

* redirect import in test_schedular.py

* first draft of module level doc

* Update docstring of fake provider v1 and v2

* Update wording of module level doc

* add fake V1 and V2 backends

* Correct fake v1 and v2 backends in the list

* comment on backends that do not have V2 versions

* list special fake backends

* Add descriptions for sections

* add code example using jupyter execute

* Update code example and improve descriptions of the module

* not using fake provider before fake provider get backend name is fixed

* modify comment

* formating fix

* Remove fake backend coupling map from docstrings

* linting

* remove coupling map of Pooughkeepsie

* add qiskit-aer to tox.ini as deps for docs build

* Revert "remove coupling map of Pooughkeepsie"

This reverts commit 4560748930.

* Revert "linting"

This reverts commit eddfa65bf6.

* Revert "Remove fake backend coupling map from docstrings"

This reverts commit 3aee7a8b57.

* fix coupling maps

* Fix minor typos

* Issue deprecation warnings from all levels of package

The previous commits in this PR did not maintain the old import paths
for submodules of `qisit.test.mock`.  This re-instatates them, with
suitable deprecation warnings.  Hopefully nobody is using these anyway,
but it's better to be on the safe side.

* Import from the correct location

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-23 02:28:30 +00:00
Naoki Kanazawa c650341a52
QPY schedule serialization (#7300)
* Schedule serialization wip

* pulse serialization

* move mapping io to separate file

* move dump numbers to parameter_values

* add alignment context serialization

* block serialization

* add interface

* bug fix

* black / lint

* documentation

* add serialization for kernel and discriminator

* migrate circuit qpy to qpy module

* keep import path

* reno

* lint

* fix import path

* update schedule qpy with cleanup. alignment classes and acquire instruction class are also updated, i.e. remove individual instance members.

* move type key enum to type_keys module

* add mapping writer (for qpy values) and cleanup sequence serializer to make sure element data is INSTRUCTION_PARAM struct.

* compress symbolic pulse expressions with zlib

* remove change to existing circuit qpy tests

* cleanup for type key

* add unittest and fix some bug
- small bug fix for wrong class usage
- exeption for None symbolic expression
- add explicit expand for symengine expression

* update documentation

* add seek(0) to data_from_binary helper function

* remove subclasses and hard coded is_sequential in every subclass

* documentation update and type fix

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* move test to own module

* update typehint

* add backward compatibility test

* fix merge and cleanup

* add circuit calibrations serialization

* fix qpy_compat test

* remove compatibility test for parameterized program

* update reno for calibrations

* fix data size

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-23 00:25:30 +00:00
Yuma-Nakamura 206ecd0e20
Add grouping by full-operator commutation relations to PauliList (#7874)
* add group_inter_qubit_commuting

* fix style lint of pauli_list.py

* fix style lint

* fix black format

* update format

* add test, docstring

* reformat

* adjust line length

* adjust docstring format

* adjust docstring format

* adjust docstring format

* update docstring and comment

* add release note

* Update documentation

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-22 23:30:03 +00:00
Matthew Treinish 5d93d8a34c
Expand instruction_supported() to optionally check parameters (#7807)
* Expand instruction_supported() to optionally check parameters

This commit expands the recently added instruction_supported() method of
the Target class to also enable optionally checking if a parameter on an
instruction is supported. This is anticipating future changes around how
instruction parameters are represented in terra more generally as part
of #7624 and specifically in the Target for #7797. Before we do any
refactoring around this having a standard API for checking if a
parameter is supported is useful. This commit expands the interface for
the insturction_supported() method to check any combination of
operation name, qargs, operation class, or parameters (either operation
name or class is required) and the method will return True if that
instruction can be run on the Target device.

* Fix docs build

* Expand test coverage

* Apply suggestions from code review

Co-authored-by: Ali Javadi-Abhari <ajavadia@users.noreply.github.com>

* Update fake backend name in tests

* Fix handling of multiple parameters in gate name case

* Fix parameter checking in class gate input case

* Add missing test path

* Add release note

* Fix release-note typo

Co-authored-by: Ali Javadi-Abhari <ajavadia@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-22 20:59:55 +00:00
Matthew Treinish 8ee4ac80ec
Add dedicated functions for memory marginalization (#8051)
* Add dedicated functions for memory marginalization

This commit adds dedicated functions for memory marginalization.
Previously, the marginal_counts() function had support for marginalizing
memory in a Results object, but this  can be inefficient especially if
your memory list is outside a Results object. The new functions added in
this commit are implemented in Rust and multithreaded. Additionally the
marginal_counts() function is updated to use the same inner Rust
functions.

* Fix rustfmt

* Add missing test file

* Fix typos

Co-authored-by: Daniel J. Egger <38065505+eggerdj@users.noreply.github.com>

* Remove unused import

* Increate default parallel_threshold to 1000

* Add support for different measurement levels

* Update docstring

* Add release note

* Expand unit tests

* Fix rustfmt

* Apply suggestions from code review

Co-authored-by: Kevin Hartman <kevin@hart.mn>

* Use a lookup table instead of a match statement

Co-authored-by: Daniel J. Egger <38065505+eggerdj@users.noreply.github.com>
Co-authored-by: Kevin Hartman <kevin@hart.mn>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-22 19:07:06 +00:00
Matthew Treinish dbc81a8dcd
Leverage Python SharedMemory for common transpile args (#7789)
* Leverage Python SharedMemory for common transpile args

This commit uses the Python shared memory library to reduce the overhead
of launching parallel processes as part of transpile. As the size of the
backends grow the payload size we're serializing and copying between
worker processes is also increasing. When we're running a lot of small
circuits at once on a big backend we can easily spend far more time
dealing with IO overhead than running the transpilation. By using shared
memory this reduces the overhead to only serializing and copying it once
and then each worker process just needs to serializing it. While this
doesn't remove all the overhead it should reduce the impact somewhat.

Fixes #7741

* Fix python 3.7 compat

* Fix approximation degree parsing

* Fix broken test

* Fix more test failures

* Simplify arg parsing logic

* Only use shared memory when running in parallel

The serialization overhead of using shared memory is only necessary when
we're running in parallel. If we're running serially there is no need to
serialize the transpiler arguments and write them to shared memory since
serially we are running the same memory space. This commit splits the
code path between serial and parallel and only uses shared memory when
we are running in parallel.

* Fix handling of ideal gates in UnitarySynthesis

The move to only having one copy of shared arguments fixed an issue in
the handling of basis gates in some cases where a list input was not
properly wrapped in a list. This was then causing UnitarySynthesis pass
to be skipped in some cases because the target basis was incomplete (and
was only a single gate) which wouldn't match any of the basis the
synthesis pass could work in. By fixing this issue with shared memory
a bug in UnitarySynthesis was exposed when trying to run the pass with
no coupling map but a Target (i.e. an ideal simulator) the pass would
fail because it assumed if there was a Target there was a coupling map
and would try to use the coupling map to find the natural direction to
synthesize the 2q gates into. This commit fixes the unitary synthesis
pass to ignore the natural direction if no coupling map is preset even
if there is a target. The test triggering this condition is then updated
to update the result to include the output of the unitary synthesis
pass.

* Fix lint failure on python 3.7

This commit fixes a lint failure on Python 3.7 by disabling a module
name check for the shared memory attributes in the multiprocessing
module. These were added in Python 3.8 and don't exist in older python
versions. For python 3.7 we use a backport library to make up for this,
but pylint doesn't know to conditionally check the stdlib import
statement as it is only used on Python >= 3.8. To avoid the failure we
just disable checking the imports from stdlib.

* Add release notes

* Relax equality check on test_target_ideal_gates opt_level 3

This commit relaxes the output circuit equality check on the optimization
level 3 variant of the test_target_ideal_gates() test. Since this branch
fixes the basis gate handling so that the UnitarySynthesis pass is
actually running now the exact output is dependent on the 2q synthesis
routine which on different platforms has subtlely different but equally
correct results based on differences in the the floating point
implementation. To avoid spurious CI failures this commit changes the
test just check the output unitary of the circuit is equivalent to the
input for optimization level 3.

* Only try to write pickle buffer length to shared memory

In CI we were seeing failures on the macOS Python 3.7 environment around
writing the pickle bytes data to the memory view of the shared memory
object that we allocated. This failure was being caused by the macOS
shared memory backport library over allocating the shared memory object
and the size of the memory view buffer being larger than the pickle
data. This caused the assignment of the pickle data to the memory view
to fail because the lengths didn't match. This commit fixes this by
explicitly only writing the bytes equal to the pickle length into
memory. This ensures no matter how big the allocated memory view is we
are always writing the correct size.

Co-Authored-By: Jake Lishman <jake.lishman@ibm.com>

* Actually commit black changes

* Remove manual manipulation of QISKIT_IN_PARALLEL

This commit removes a leftover from earlier iterations of the PR that
were manually manipulation of QISKIT_IN_PARALLEL. This was done earlier
in the PR branch because parallel_map was manually replaced with
multiprocessing directly. However, after refining the use of shared
memory this wasn't needed and parallel_map was used instead.

* Remove unecessary optimization_level storage

* Update docs and type hints

* Remove unnecessary list cast for basis gates

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-22 12:03:35 +00:00
Julien Gacon cbb64ed266
Remove deprecated `optimize` from `Optimizer` (and small other fixes) (#8123)
* Remove deprecated methods from Optimizers

* `optimize` method is superseded by `minimize`
* SPSA didn't trigger the deprecation warning, so it's included now
* The `factr` attribute in `P_BFGS` was deprecated 13 months ago

* add reno

* Apply suggestions from code review

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Fix lint and reno

* change meth to attr in reno

* remove logic for Optimizer.optimize in VQE

* lint

* address comments from review

* Fix lint

This commit fixes the pylint failures. Two for unused imports and the
third was a to disable a broken check in pylint where it was complaining
about a multiline string being a docstring without """ quotes.

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-22 02:13:28 +00:00
Jake Lishman ea02667698
Change data type of `QuantumCircuit.data` elements (#8093)
* Convert QuantumCircuit.data items to CircuitInstruction

This introduces a new, lightweight class `CircuitInstruction` the
encapsulates the previous 3-tuple that made up the items of
`QuantumCircuit.data`.  It includes a legacy API that makes the object
appear to be the old 3-tuple when used as if it were that tuple, and the
relatively small changeset for this commit is an approximate indication
that these should mostly be suitable.  There will be significant
performance penalties for accessing the legacy interface, however, due
to some internal type conversions, so it is a matter of priority to
convert internal usage to the new dotted-attribute access form.

The only places necessary to change across Terra were those where the
data elements were compared by referential equality to expected values
(such as in the control-flow builders), and places that were invalidly
accessing the private attribute `QuantumCircuit._data`.  All these are
updated.

`ParameterTable` should in the future be changed to operate over this
entire context, but that was beyond the scope of the initial commit.

* Convert all usage of data tuple to CircuitInstruction

This previous commit is the minimal set of changes needed for the entire
test suite to pass, but large parts of Terra and the test suite were
still using the backwards-compatibility shims when dealing with
`QuantumCircuit.data`.  This changes over every single usage within
Terra to use the new dotted-access form, rather than the tuple indexing
or iteration that previously existed.

The internal types of the `qargs` and `cargs` in `DAGDepNode` and
`DAGOpNode` are also changed to be `tuple` now; previously they were
semi-undefined, and in some cases were not consistent, but not caught in
the test suite.  Since changing the type of the `qubits` parameter in
`CircuitInstruction` to be tuple (unless using the
backwards-compatibility shims), this caused a lot of failures where the
value was being assigned directly.  Normalising to `tuple` has the same
benefit as it does in the circuit instruction - less copying overhead,
and no worrying about multiple writable references to the same object.

By far the largest set of changes are in the test suite; we do a lot of
comparing things for exact equality, and since the type is now changed
from `list` to `tuple`, all the tests had to be updated.  This isn't
expected to have much impact on user code, but changing the type to an
immutable one has large benefits for us when copying these data
structures.

* Correct bad version in comment

* Simplify unnecessary if/else

* Update remnant legacy interface uses

Some uses of the legacy interface related to directly setting
`QuantumCircuit.data` had slipped through the cracks.  A bug in
`astroid` caused its inference to fail, and think that these settings
made the scalar type of `QuantumCircuit.data` the old 3-tuple after it
saw these settings.  Since there's a property setter for `data`, that's
a bug in `astroid`, but it still turned up some useful additional cases
that were useful to correct.

* Remove accidental blank line

* Use QuantumCircuit.copy_empty_like in Instruction constructors

* Correct global phase in Instruction.inverse

* Shut pylint up about consider-using-generator

pylint isn't actually correct in this case.  `tuple(<list comp>)` is
more efficient than `tuple(<generator>)` (certainly as of Python 3.10),
because Python still needs to use a temporary vector-like expanding
collection while consuming the iterable so despite appearances there's
no memory benefit to the generator, and list comprehensions are
translated into faster bytecode than general generators.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-21 23:51:21 +00:00
Matthew Treinish 42c72be193
Fix BackendV2 support for PassManagerConfig.from_backend() (#8109)
This commit fixes the PassManagerConfig.from_backend() constructor
method when running with a BackendV2 object. Previously this was not
correctly handled and it always assumed the input backend was a
BackendV1 object. This would cause an error if you ran the constructor
with a BackendV2.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-21 22:31:06 +00:00
Kevin J. Sung 992c2619d6
Edit Result to always contain date, status, header (#8216)
* date attribute

Date attribute is needed for some specific applications such as mitigation in mthree. It is not created by default when running a job in the basicAer backend.

* Update test_result.py

* Adding default attributes header and status

I have no clue why in the test_results the attribute status is repeated.

* fix Result repr

* add release note

* Qualify method name in release note

* Remove final conditional attribute lookup on Result

Co-authored-by: Alejandro Montanez <alejomonbar@gmail.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-21 20:53:29 +00:00
Matthew Treinish 71495591d7
Add StagedPassManager class for pass manager with defined stages (#6403)
* Add FullPassManager class for pass manager with defined stages

This commit adds a new PassManager subclass, FullPassManager. This class
is used to have a PassManager with a defined structure and stages for
the normal transpile workflow. The preset pass managers are then updated
to be FullPassManager objects they conform to the fixed structure. Having
a class with defined phases gives us flexibility in the future for making
the transpiler pluggable with external plugins (similar to what's done in
PR #6124) and also have backend hook points before or after different
phases of the transpile.

Fixes #5978

* Add docs

* Deduplicate preset passmanager construction

* Update docs

* Add dedicated scheduling stage to FullPassManager

* Add missing new UnitarySynthesis kwargs after rebase

* Use basis_translator as default method instead of basis

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Rename FullPassManager StructuredPassManager

* Rename generate_scheduling_post_opt() generate_scheduling()

* Fix missing and incorrect arguments

* Fix more rebase issues

* Fix even more rebase issues

* Only run unroll3q on level 0-2 if coupling map is set

To preserve the behavior prior to this reorganization this commit makes
the Unroll3qorMore pass run if we have a coupling map set. This is
because this pass is only needed to be run for these optimization levels
so that the layout and routing passes can function (as they only work
with 2q gates). If we're not running these passes we shouldn't be
unrolling gates. This will fix the last 4 QAOA test failures post the
recent rebase as that was failing because we were trying to unroll an
unbound 4q hamiltonian gate when weren't before.

* Rework StructuredPassManager as a more dynamic StagedPassManager

This commit redefines the previous StructuredPassManager class into a
more dynamic StagedPassmanager. The StagedPassManager doesn't have fixed
hard coded stages anymore but instead lets users define their own
stages. It also adds implicit 'pre_' and 'post_' hook points for each
listed stage. This lets users dynamically define the stages based on a
particular use case.

* Fix docs

* Update internal pass set on each access

This commit updates the api for the StagedPassManager to refresh the
internal pass list on each access. This adds a little overhead but with
the tradeoff of making in place modifications to a stage's pass manager
reflected without needing to manually call an update method.

* Rename phases attribute to stages

* Fix lint

* Explicitly set name in qpy compat tests

The rework of the preset passmanager construction changes the import
order slightly and the number of circuits constructed in a session prior
to the qpy compat deserialization side generating equivalent circuits
for comparision has changed. This is causing all the deserialization
side numbers to change and the tests are now failing because the circuit
names are not equivalent. Since the exact name is a side effect of the
import order (based on the number of unnamed circuits created in the
session priort) it's not part of what the qpy tests are validating.
We're trying to assert that the naem is preserved loading a qpy file
across a version boundary. To fix this issues this commit adds an
explicit name to the generation for all the circuits to ensure that we
have a deterministic name for each circuit.

* Apply suggestions from code review

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* Run black

* Update type hint

* Remove out of date docstring note

* Update copyright header date in qiskit/transpiler/preset_passmanagers/common.py

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* Add check for invalid stage names

* Add backwards compatibility note

* Add docs on using StagedPassManager features with preset passmanagers

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-21 18:57:04 +00:00
Frank Harkins 4414c4eca6
Pass `max_size` to Statevector LaTeX drawer (#8197)
* Fix #7516

* Remove unused import

* Improve splitting of string literals

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-21 16:17:04 +00:00
Jake Lishman 0e3e68d162
Speedup constant factors in `LookaheadSwap` (#8068)
* Speedup constant factors in `LookaheadSwap`

This picks some of the low-hanging fruit in `LookaheadSwap`, avoiding
recalculating various properties and entities that are already known,
and making some access patterns more efficient.  It does not change the
complexity properties of the algorithm, which will still cause its
runtime to be excessive for large circuits.

* Put comment in correct location

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-21 15:02:21 +00:00
Matthew Treinish a34f0ce1ec
Fix handling of ControlledGates in QPY (#8055)
* Fix handling of ControlledGates in QPY

This commit fixes the handling of ControlledGates in QPY. Previously the
extra parameters needed to reconstruct a custom controlled gate were not
encoded into the QPY payload. Fixing this required a version bump to the
QPY format to modify the payload for a custom instruction entry. Once we
added to the format the extra data required for a controlled gate, the
number of control qubits, the control state, and the base gate object,
the deserializer has enough information to recreate the custom
ControlledGate objects. However, fixing this exposed another bug with
standard library multicontrolled gates where they often didn't contain
sufficient data in the payload to reconstruct either.

Fixes #7999

* Fix test failure caused by missing condition

This commit fixes the qpy test failure. This was caused by the omission
of the classical condition on a controlled gate when reconstructing the
circuit in deserialization. Fixing this oversight fixes the test
failures.

* Add QPY version 5 payload format description

* Add release note

* Expand test coverage

* Only check controlled gate type key on version 5 or newer

* Fix mcu1 deserialization

* Add copy to avoid mutating list while iterating over it

* Fix compat test minimum version

This commit fixes the failing compat test which was incorrectly trying
to test ControlledGates with 0.20.2 generation. We should only run the
controlled gate tests starting with 0.21.0.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-17 23:50:55 +00:00
Matthew Treinish 186c807877
Explicitly set MSRV for rust extension (#8196)
* Explicitly set MSRV for rust extension

This commit explicitly sets the MSRV (minimum supported rust version)
for Qiskit Terra to 1.56 which was released in October 2021 (with 1.56.1
which fixed two CVEs being released Nov. 1st 2021). Previously we had
avoided setting a hard MSRV and opted to try and just loosely support the
past 6 months of rust releases. However, managing it loosely has proven
tricky to manage in practice. This commit sets a hard version for MSRV
and modifies a test job to validate we're able to compile with the MSRV.
This should ensure we're able to avoid breaking compatibility for that
version.

* Explicitly set MSRV to 1.56.1 instead of loosely 1.56

* Explicitly set version as variable in CI config

* Assign MSRV to azure variable

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-17 19:20:42 +00:00
Pedro Rivero f47cd45e29
Add `.clear()` and `.copy_empty_like()` functionality to QuantumCircuit. (#8134)
* Add .copy_empty_like and .clear to QuantumCircuit

* Simplify copy_empty_like in QuantumCircuit

* Update docstring for copy_empty_like in QuantumCircuit

* Deepcopy global_phase for copy_empty_like in QuantumCircuit

* Add tests and refactor

* Add release note

* Add .copy_empty_like and .clear to QuantumCircuit

* Simplify copy_empty_like in QuantumCircuit

* Update docstring for copy_empty_like in QuantumCircuit

* Deepcopy global_phase for copy_empty_like in QuantumCircuit

* Add tests and refactor

* Add release note

* Update docstring

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update docstring

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update docstring

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update test to check metadta and calibrations

* Add tests for circuit name

* Update releasenotes/notes/clear-circuit-b8edd4126f47d75a.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-16 23:10:01 +00:00
Tan Jun Liang bcd98951ea
decompose(reps=1) repeating decompose (#8142)
* decompose() repeat decompose

https://github.com/Qiskit/qiskit-terra/issues/8139#issue-1261865139   
summary:
```
circuit.decompose(reps = 5) # repeat decompose 5 times
```

* add reps parameters

forgot

* Update quantumcircuit.py

* Update qiskit/circuit/quantumcircuit.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update quantumcircuit.py

* Update quantumcircuit.py

* Update blueprintcircuit.py

* Update blueprintcircuit.py

* fixing some bug

fixed also: https://github.com/Qiskit/qiskit-terra/issues/5974#issue-823183659
but need to fix label gate repeat decompose not working.

* Update decompose.py

* Update decompose.py

* fix https://github.com/Qiskit/qiskit-terra/issues/5974

* Update decompose.py

* test_case & fix decompose repeat work with multi_gate

* Update test_decompose.py

* Update test_decompose.py

* Update test_decompose.py

* Update decompose.py

* Update decompose.py

* Update decompose.py

* Update test_decompose.py

* fix lint

* Update decompose.py

* fix lint

* change back preset

* changing back

* Update quantumcircuit.py

* original version

* release_note

* Update releasenotes/notes/add-parameters-to-decompose-5a541d1b5afe2c68.yaml

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update add-parameters-to-decompose-5a541d1b5afe2c68.yaml

* Update add-parameters-to-decompose-5a541d1b5afe2c68.yaml

* Update releasenotes/notes/add-parameters-to-decompose-5a541d1b5afe2c68.yaml

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Update releasenotes/notes/add-parameters-to-decompose-5a541d1b5afe2c68.yaml

Co-authored-by: Jake Lishman <jake@binhbar.com>

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-16 21:20:11 +00:00
Naoki Kanazawa 7391168c89
Cleanup timeline drawer with schedule analysis pass. (#7935)
* Cleanup timeline and add schedule info to scheduled circuit.

* review comment

* fix bug

* review comments

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* lint

* disable cyclic import lint check (likely a bug)

* fix import path

* Revert "fix import path"

This reverts commit 1fa5382df4.

* fix bug

* add deprecation for unscheduled circuit drawing

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-16 17:00:14 +00:00