* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
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>
* 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>
* 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>
* 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>
* 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
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* fix an issue of transpile of BackendSampler
* optimize
* add reno
* updated test
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
* 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>
* 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
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
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>
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>
* 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>
* 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
* 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>
* 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>
* 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>
* 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>
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>
* 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>
The `add_nodes` call should be outside the loop; inside, it adds nodes
quadratically. This commit also squashes a minor inefficiency in set
allocation.
* 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>
* 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
* 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>
* 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>
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>
* 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>
* 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>
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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
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>
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>
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>
* 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>
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).
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>
* 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
* 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>
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>
* 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
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>
* 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
* 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>
* 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.
* 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>
* 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>
* 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>
* 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>
* "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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* fix flipping of the symmetric cz gate
* complete test
* black
* pylint
* black
* add release notes
Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
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>
* 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>
* 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>
* deprecate deprecated_functionality
* pylint: disable=cyclic-import
* Add reno
* Include Terra version in deprecation notice
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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)
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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.
* 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>
* 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>
* 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>
* 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>
* 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>
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>
* 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
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
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>
* 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>
* 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>
* 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>
* 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>
* 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>