Commit Graph

3601 Commits

Author SHA1 Message Date
Alexander Ivrii 2245a4f44b
Fix qft-plugins for custom 'qft' gates (#13181) 2024-09-19 15:43:19 +00:00
Jake Lishman ece25b6b5d
Make `qasm3.CustomGate` accessible from Python space (#13187)
We previously exposed the data attribute `STDGATES_INC_GATES`, but its
contents are all `CustomGate`, which can't be inspected programmatically
from Python space.  This makes it so you can query _what_ the gates,
their number of parameters, and how to construct them.
2024-09-19 13:38:07 +00:00
Jake Lishman 5121a0fda8
Re-allow non-standard includes in OpenQASM 3 exporter (#13148)
Swapping the behaviour of the exporter to error on unknown includes was
a mistake, and a breaking change from previous versions of the OpenQASM
3 exporter, since the `basis_gates` argument can be used to emulate the
expected behaviour of this option, even though the previously documented
behaviour was never actually fulfilled.

This restores the previous non-erroring behaviour, and corrects the
documentation to note how the ``includes`` argument should be used in
the near term.
2024-09-18 23:13:10 +00:00
Shelly Garion 653b5b66f5
Clean two_qubit_decompose code (#13093)
* add pyfunction for decompose_two_qubit_product_gate

* replace python code by rust for decompose_two_qubit_product_gate

* remove unused code from two_qubit_decompose.py

* updates following review comments

* port trace_to_fid to rust

* port Ud to rust

* fix lint errors

* fix lint errors

* format

* remove PyResult following review
2024-09-13 14:35:03 +00:00
Julien Gacon 1ff6361303
Oxidize `PauliFeatureMap` (#13045)
* port PauliFeatureMap to Rust

* more docs, less error expecting

* cleanup, docstrings

* clippy & speedup

* base for dictionary entanglement

* rm unnecessary pub

* add reno

* refactor ``rmultiply_param``

* fix & test dict entanglement

* clippy

* Refactor Rust code a bit

- improve readability
- only create barrier if necessary

* RIP iterators (for proper error handling)

performance seems to be unaffected :)
2024-09-12 13:07:26 +00:00
Luciano Bello 2fa6dd65d6
deprecate BackendV1 in `PassManagerConfig.from_backend` (#12931)
* deprecate BackendV1 in  PassManagerConfig.from_backend

* test.python.transpiler.test_passmanager_config

* primitives/test_backend_estimator_v2

* test.python.primitives.test_backend_estimator_v2.TestBackendEstimatorV2

* res
2024-09-12 08:10:31 +00:00
Julien Gacon f2ca9205e3
Fix an edge case in Sabre's release valve (#13114)
* Fix edge case in Sabre release valve

If a Sabre trial does not find a set of Swaps to route nodes, the "release valve" adds Swaps to route the two-qubit gate in between the the closest two qubits. In rare cases, this leads to _more_ than one gate being routable, which was not handled correctly previously.

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

* add reno and test

* Use sensible syntax

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

* Use sensible grammar

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

* clippy

* Check if the new test breaks CI

* Revert "Check if the new test breaks CI"

This reverts commit 01bcdc7ca2.

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Kevin Hartman <kevin@hart.mn>
2024-09-11 11:55:41 +00:00
Matthew Treinish dd145b54be
Raise minimum python version to 3.9 (#12910)
* Raise minimum python version to 3.9

Qiskit 1.2.0 was the final minor version release of qiskit with Python
3.8 support. As Python 3.8 is going EoL before the next Qiskit minor
release 1.3.0 we can drop support for running with 3.8 on the main
branch now. This commit makes that change and updates everything using
python 3.8 currently to use our new minimum instead.

* Pin dependency versions when installing historical versions

Now that we're running Python 3.9 as the base version we are
encountering compatibility issues with some of our dependencies because
3.9 supports newer versions of things like numpy than older Qiskit
releases were compatible with. The only way to work around this is to
pin the versions when installing historical versions. To start this sets
a single constraints version since we can get away with using the same
version for everything. In the future though it is possible that we'll
need separate files for different historical releases.

* Update reference images

* Drop 3.8 support in asv too

* Remove deprecation warning for 3.8
2024-09-10 23:53:20 +00:00
Sebastian Brandhofer 49b8a5fe9a
Oxidize commutative cancellation (#13091)
* fix

* fmt

* comments from code review

* comments from code review

* Update lib.rs

* Apply suggestions from code review

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

* code review

* Fix rustfmt

* Don't change interface for DAGCircuit

Previously this PR was making the op_names field of the DAGCircuit
struct public so it was accessible to the new transpiler pass code.
However, this opened up the possibility of mutating the field by
mistake, instead this makes the field private again and adds a no-copy
method to get an immutable reference to the field. Additionally, there
were some interface changes made to one method in DAGCircuit that were
not needed anymore, which this reverts to minimize the diff.

* Remove last .first().unwrap()

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2024-09-10 18:51:28 +00:00
Julien Gacon 8929e12bab
Fix the matrix representation of CUGate in Rust (#13121)
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2024-09-10 15:30:00 +00:00
Julien Gacon 1962704cf1
Fix creation of registers in synthesis methods (#13086)
* add qregs to output circuits

* never develop while not on up-to-date main

* one shan't commit faster than ones IDE can run black

* avoid compose
2024-09-10 14:22:33 +00:00
Julien Gacon d14eb9c482
Fix skipping of slow tests (#13119) 2024-09-10 14:10:24 +00:00
Jake Lishman 3aa58cc2ab
Add equivalence-library rules between `rzz` and `cp` (#13019)
* Add equivalence-library rules between `rzz` and `cp`

These gates are locally equivalence (as are all the Ising-interaction
gates), and this simple additional rule lets things like QFT, which are
defined by Qiskit's default constructor in terms of `cp`, get converted
into `rzz` or `rzx`.

One `ControlledGate` test needed a case removing, because the underlying
control mechanism now works correctly.

* Rewrite release note
2024-09-09 08:49:41 +00:00
Eli Arbel 734560e6c9
Oxidize CheckGateDirection (#13042)
* First working implementation

* A control flow fix, lint, doc and some more polishing

* Addressing review comments and further simplifying the code

* Address more review comments

* Use explicit temp storage for mapping to avoid E0716 in Rust 1.70

* Allow checking 2Q non-control flow instructions
2024-09-08 12:10:30 +00:00
Julien Gacon 9898979d29
Restrict `Split2QUnitaries` to run on `UnitaryGate` (#13095) 2024-09-05 16:34:48 +00:00
Shelly Garion 8606f058c8
Port RemoveDiagonalGatesBeforeMeasure to rust (#13065)
* add rust code for remove_diagonal_gates_before_measure

* replace python code by rust code for remove_diagonal_gates_brefore_measure

* make some dag_circuit functions public

* fix some of the tests failures

* fix another failing test, add more diagonal gates

* add tests for added diagonal gates: p, cp, cs, csdg

* make the lists of diagonal gates into static arrays

* formatting

* change nodes_to_remove type to Vec

* remove the HashSet following review

* add CCZ diagonal gate

* add tests for CCZ diagonal gate

* add release notes

* fix lint
2024-09-05 12:20:17 +00:00
Matthew Treinish 52733ae09f
Adjust graphviz options for better layout with plot_gate_map() (#12770)
* Adjust graphviz options for better layout with plot_gate_map()

This commit fixes an issue with the visualizations of some
backends/coupling maps. The default neato settings worked well in most
cases but for some graphs it was not generating a good layout. This
tweaks the settings a bit so that layouts work with more classes of
graphs.

* Don't set graph attributes if qubit_coordinates is set

* adjust sizes

* planar branching

* support for backendv1

* remove the formula

* new ref images

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-09-05 08:20:32 +00:00
Alexander Ivrii 576efcf14a
Bug fix in `HoareOptimizer` (#13083)
* bug fix, test, reno

* suggestions from code review; lint
2024-09-04 15:32:52 +00:00
Matthew Treinish dde09f9d62
Remove benchmarks for deprecated (or soon to be) features (#13064)
This commit removes benchmarks for the deprecated assemble module and
the soon to be (see #13063) deprecated pulse module. While these
features are still supported it's not worth the spending the limited
CPU time we hacve on the benchmarking system to track the performance of
these components anymore.
2024-09-03 13:46:48 +00:00
Jake Lishman 8f3308475c
Fix extraction of controlled parametric gates (#13067)
The `mutable` check in the controlled-gate `OperationFromPython`
extraction logic to check for a mutated `base_gate` was overzealous,
and would return false positives for parametric controlled gates.  The
only modification to `base_gate` of a standard-library gate that would
not have caused data-model problems from Python space would be setting
the base-gate label, which is used for a public feature of the circuit
visualisers.

The change to `get_standard_gate_name_mapping` is just a minor
convenience to make the gate objects directly appendable to a circuit;
previously, each `Parameter` object was distinct and had a UUID clash
with others of the same name, so could not be used together.  The new
behaviour is purely a convenience for tests; it largely should not be
useful for users to directly append these gates.
2024-09-03 13:46:34 +00:00
Sebastian Brandhofer df0ad77fd5
Oxidize commutation checker (#12870)
* init

* up

* lint

* .

* up

* before cache

* with cache

* correct

* cleaned up

* lint reno

* Update Cargo.lock

* .

* up

* .

* revert op

* .

* .

* .

* .

* Delete Cargo.lock

* .

* corrected string comparison

* removed Operator class from operation.rs

* .

* Apply suggestions from code review

Co-authored-by: Raynel Sanchez <87539502+raynelfss@users.noreply.github.com>

* comments from code review

* Apply suggestions from code review

Co-authored-by: Raynel Sanchez <87539502+raynelfss@users.noreply.github.com>

* code review

* remove with_gil in favor of passing python tokens as params

* Apply suggestions from code review

Co-authored-by: Raynel Sanchez <87539502+raynelfss@users.noreply.github.com>

* fmt

* python serialization

* deprecation

* Update commutation_checker.py

* heh

* let Pytuple collect

* lint

* First set of comments

- use Qubit/Clbit
- more info on unsafe
- update reno
- use LazySet less
- use OperationRef, avoid CircuitInstruction creation

* Second part

- clippy
- no BigInt
- more comments

* Matrix speed & fix string sort

-- could not use op.name() directly since sorted differently than Python, hence it's back to BigInt

* have the Python implementation use Rust

* lint & tools

* remove unsafe blocks

* One more try to avoid segfaulty windows

-- if that doesn't work maybe revert the change the the Py CommChecker uses Rust

* Debug: disable cache

trying to figure out why the windows CI fails (after being unable to locally reproduce we're using CI with a reduced set of tests)

* ... second try

* Update crates/accelerate/src/commutation_checker.rs

Co-authored-by: Raynel Sanchez <87539502+raynelfss@users.noreply.github.com>

* Restore azure config

* Remove unused import

* Revert "Debug: disable cache"

This reverts commit c564b806c9.

* Don't overallocate cache

We were allocating a the cache hashmap with a capacity for max cache
size entries every time we instantiated a new CommutationChecker. The
max cache size is 1 million. This meant we were allocating 162MB
everytime CommutationChecker.__new__ was called, which includes each
time we instantiate it manually (which happens once on import), the
CommutationAnalysis pass gets instantiated (twice per preset pass
manager created with level 2 or 3), or a commutation checker instance is
pickle deserialized. This ends up causing a fairly large memory
regression and is the source of the CI failures on windows.

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

* Cleanup parameter key type to handle edge conditions better

This commit cleans up the ParameterKey type and usage to make it handle
edge conditions better. The first is that the type just doesn't do the
right thing for NaN, -0, or the infinities. Canonicalization is added
for hash on -0 and the only constructor of the newtype adds a runtime
guard against NaN and inifinity (positive or negative) to avoid that
issue. The approach only makes sense as the cache is really there to
guard us against unnecessary re-computing when we reiterate over the
circuit > 1 time and nothing has changed for gates. Otherwise comparing
floats like done in this PR does would not be a sound or an effective
approach.

* Remove unnecessary cache hit rate tracking

* Undo test assertion changes

* Undo unrelated test changes

* Undo pending deprecation and unify commutation classes

This commit removes the pending deprecation decorator from the python
class definition as the Python class just internally is using the rust
implementation now. This also removes directly using the rust
implementation for the standard commutation library global as using the
python class is exactly the same now.

We can revisit if there is anything we want to deprecate and remove in
2.0 in a follow up PR. Personally, I think the cache management methods
are all we really want to remove as the cache should be an internal
implementation detail and not part of the public interface.

* Undo gha config changes

* Make serialization explicit

This commit makes the pickling of cache entries explicit. Previously it
was relying on conversion traits which hid some of the complexity but
this uses a pair of conversion functions instead.

* Remove stray SAFETY comment

* Remove ddt usage from the tests

Now that the python commutation checker and the rust commutation checker
are the same thing the ddt parameterization of the commutation checker
tests was unecessary duplication. This commit removes the ddt usage to
restore having a single run of all the tests.

* Update release note

* Fix CommutationChecker class import

* Remove invalid test assertion for no longer public attribute

* Ray's review comments

Co-authored-by: Raynel Sanchez <raynelfss@hotmail.com>

* Handle ``atol/rtol``, more error propagation

* re-use expensive quantities

such as the relative placement and the parameter hash

---------

Co-authored-by: Raynel Sanchez <87539502+raynelfss@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Julien Gacon <jules.gacon@googlemail.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Raynel Sanchez <raynelfss@hotmail.com>
2024-09-03 13:37:57 +00:00
tglanz b501db1e21
skip test unless HAS_PIL (#13077) 2024-09-03 13:35:31 +00:00
Alexander Ivrii f882fd53d3
Oxidize random clifford (#12695)
* starting to experiment

* porting code

* messy code porting

* printing statements to enable debugging

* fixes

* fixing phase

* removing some of the printing statements

* fixing inaccuracy for cost computation

* Moving some of the functionality to SymplecticMatrix class

* reducing the number of warnings

* formatting

* replacing expensive adjoint and compose operations for symplectic matrices by significantly cheaper in-place prepend operations

* resolving merge conflicts

* cleanup

* code cleanup

* cleanup

* cleanup

* cleanup

* cleanup

* cleanup

* cleanup

* cleanup

* using fast lookup

* cleanup

* clippy

* including params in gate_seq to avoid mapping

* removing unnecessary inner function

* cleanup

* renaming

* changes on the python side

* reno

* adding error handling

* improved error handling

* removing redundant Ok(Some(...))

* using random_clifford in tests

* reorganizing clifford code

* fixes

* formatting

* improved error handling

* do not panic

* formatting

* initial implementation

* cleanup

* changing return to be the full tableau

* parallelized computation for binary matrix multiplication for matrices with >= 10 qubits

* updating python code and adding release notes

* lint, test, reno

* removing obsolete python code

* removing todo (after experimenting with alternative implementation)

* removing another obsolete todo

* unused import

* adding comment
2024-09-03 11:10:01 +00:00
Shravan Patel f30f851c98
Fixed ZZFeatureMap not accepting a list of entanglement (#12767)
* Added a get_entangler_map() and _selective_entangler_map() functions to PauliFeatureMap

* Added some logic to handle the List[List[List[List[int]]]] case. Refer to the comments in the code.

* `entanglement` can now be specified as dictionary `{num_qubits: entanglement}`

* Added logic to handle cases when entanglement is not specified for some pauli blocks.

* Added tests cases for `PauliFeatureMap`

* Added test and releasenotes. Also modified the typing hints and doc strings to reflect new changes.

* Replaced all tab characters with spaces to fix the linting error.

* Formatted releasenotes as per the suggestion to fix the issue in reno.

* Added `Callable[[int], Union[str | Dict[...]]]` to the typing hints and included some logic to handle that.

* Removed `List[List[int]]` from typing hints as this is equivalent to List[Tuple[int]]

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

* updated the release notes

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

* Updated typing hints in `ZZFeatureMap`

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2024-09-03 07:51:38 +00:00
Elena Peña Tapia 623415cdb7
Fix use of `node.op` in `Split2QUnitaries` (#13015)
* Replace node.op with node.matrix

* Add docstring to test gate

* Fix black
2024-08-30 19:10:26 +00:00
Timothée Dao 83ecf39656
Fix `UnitaryGate.repeat()` method (#12986)
* fix: deal with special case for `UnitaryGate`

* add test

* add release note

* typo

* generalize the fix to other gates

* fix seeds

* update unittests

* Add missing unittests

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-08-26 08:17:49 +00:00
Julien Gacon 54ac8f1751
Move the circuit library's entanglement logic to Rust (#12950)
* Move ``get_entangler_map`` to Rust

* add reno

* add docs, better arg order

* clippy

* add docs to make reviewers happier

* use Itertools::combinations

thanks @alexanderivrii for the hint!

* avoid usage of convert_idx

* implement reviews

* implement review comments

* rm unused import
2024-08-26 07:35:41 +00:00
Kevin Hartman d3040a0b7f
[DAGCircuit Oxidation] Port `DAGCircuit` to Rust (#12550)
* Port DAGCircuit to Rust

This commit migrates the entirety of the `DAGCircuit` class to Rust. It
fully replaces the Python version of the class. The primary advantage
of this migration is moving from a Python space rustworkx directed graph
representation to a Rust space petgraph (the upstream library for
rustworkx) directed graph. Moving the graph data structure to rust
enables us to directly interact with the DAG directly from transpiler
passes in Rust in the future. This will enable a significant speed-up in
those transpiler passes. Additionally, this should also improve the
memory footprint as the DAGCircuit no longer stores `DAGNode`
instances, and instead stores a lighter enum NodeType, which simply
contains a `PackedInstruction` or the wire objects directly.

Internally, the new Rust-based `DAGCircuit` uses a `petgraph::StableGraph`
with node weights of type `NodeType` and edge weights of type `Wire`. The
NodeType enum contains variants for `QubitIn`, `QubitOut`, `ClbitIn`,
`ClbitOut`, and `Operation`, which should save us from all of the
`isinstance` checking previously needed when working with `DAGNode` Python
instances. The `Wire` enum contains variants `Qubit`, `Clbit`, and `Var`.

As the full Qiskit data model is not rust-native at this point while
all the class code in the `DAGCircuit` exists in Rust now, there are
still sections that rely on Python or actively run Python code via Rust
to function. These typically involve anything that uses `condition`,
control flow, classical vars, calibrations, bit/register manipulation,
etc. In the future as we either migrate this functionality to Rust or
deprecate and remove it this can be updated in place to avoid the use
of Python.

API access from Python-space remains in terms of `DAGNode` instances to
maintain API compatibility with the Python implementation. However,
internally, we convert to and deal in terms of NodeType. When the user
requests a particular node via lookup or iteration, we inflate an ephemeral
`DAGNode` based on the internal `NodeType` and give them that. This is very
similar to what was done in #10827 when porting CircuitData to Rust.

As part of this porting there are a few small differences to keep in
mind with the new Rust implementation of DAGCircuit. The first is that
the topological ordering is slightly different with the new DAGCircuit.
Previously, the Python version of `DAGCircuit` using a lexicographical
topological sort key which was basically `"0,1,0,2"` where the first
`0,1` are qargs on qubit indices `0,1` for nodes and `0,2` are cargs
on clbit indices `0,2`. However, the sort key has now changed to be
`(&[Qubit(0), Qubit(1)], &[Clbit(0), Clbit(2)])` in rust in this case
which for the most part should behave identically, but there are some
edge cases that will appear where the sort order is different. It will
always be a valid topological ordering as the lexicographical key is
used as a tie breaker when generating a topological sort. But if you're
relaying on the exact same sort order there will be differences after
this PR. The second is that a lot of undocumented functionality in the
DAGCircuit which previously worked because of Python's implicit support
for interacting with data structures is no longer functional. For
example, previously the `DAGCircuit.qubits` list could be set directly
(as the circuit visualizers previously did), but this was never
documented as supported (and would corrupt the DAGCircuit). Any
functionality like this we'd have to explicit include in the Rust
implementation and as they were not included in the documented public
API this PR opted to remove the vast majority of this type of
functionality.

The last related thing might require future work to mitigate is that
this PR breaks the linkage between `DAGNode` and the underlying
`DAGCirucit` object. In the Python implementation the `DAGNode` objects
were stored directly in the `DAGCircuit` and when an API method returned
a `DAGNode` from the DAG it was a shared reference to the underlying
object in the `DAGCircuit`. This meant if you mutated the `DAGNode` it
would be reflected in the `DAGCircuit`. This was not always a sound
usage of the API as the `DAGCircuit` was implicitly caching many
attributes of the DAG and you should always be using the `DAGCircuit`
API to mutate any nodes to prevent any corruption of the `DAGCircuit`.
However, now as the underlying data store for nodes in the DAG are
no longer the python space objects returned by `DAGCircuit` methods
mutating a `DAGNode` will not make any change in the underlying
`DAGCircuit`. This can come as quite the surprise at first, especially
if you were relying on this side effect, even if it was unsound.

It's also worth noting that 2 large pieces of functionality from
rustworkx are included in this PR. These are the new files
`rustworkx_core_vnext` and `dot_utils` which are rustworkx's VF2
implementation and its dot file generation. As there was not a rust
interface exposed for this functionality from rustworkx-core there was
no way to use these functions in rustworkx. Until these interfaces
added to rustworkx-core in future releases we'll have to keep these
local copies. The vf2 implementation is in progress in
Qiskit/rustworkx#1235, but `dot_utils` might make sense to keep around
longer term as it is slightly modified from the upstream rustworkx
implementation to directly interface with `DAGCircuit` instead of a
generic graph.

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Raynel Sanchez <87539502+raynelfss@users.noreply.github.com>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>
Co-authored-by: Eli Arbel <46826214+eliarbel@users.noreply.github.com>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>

* Update visual mpl circuit drawer references

Right now there is a bug in the matplotlib circuit visualizer likely
caused by the new `__eq__` implementation for `DAGOpNode` that didn't
exist before were some gates are missing from the visualization. In the
interest of unblocking this PR this commit updates the references for
these cases temporarily until this issue is fixed.

* Ensure DAGNode.sort_key is always a string

Previously the sort_key attribute of the Python space DAGCircuit was
incorrectly being set to `None` for rust generated node objects. This
was done as for the default path the sort key is determined from the
rust domain's representation of qubits and there is no analogous data in
the Python object. However, this was indavertandly a breaking API change
as sort_key is expected to always be a string. This commit adds a
default string to use for all node types so that we always have a
reasonable value that matches the typing of the class. A future step is
likely to add back the `dag` kwarg to the node types and generate the
string on the fly from the rust space data.

* Make Python argument first in Param::eq and Param::is_close

The standard function signature convention for functions that take a
`py: Python` argument is to make the Python argument the first (or
second after `&self`). The `Param::eq` and `Param::is_close` methods
were not following this convention and had `py` as a later argument in
the signature. This commit corrects the oversight.

* Fix merge conflict with #12943

With the recent merge with main we pulled in #12943 which conflicted
with the rust space API changes made in this PR branch. This commit
updates the usage to conform with the new interface introduced in this
PR.

* Add release notes and test for invalid args on apply methods

This commit adds several release notes to document this change. This
includes a feature note to describe the high level change and the user
facing benefit (mainly reduced memory consumption for DAGCircuits),
two upgrade notes to document the differences with shared references
caused by the new data structure, and a fix note documenting the fix
for how qargs and cargs are handled on `.apply_operation_back()` and
`.apply_operation_front()`. Along with the fix note a new unit test is
added to serve as a regression test so that we don't accidentally allow
adding cargs as qargs and vice versa in the future.

* Restore `inplace` argument functionality for substitute_node()

This commit restores the functionality of the `inplace` argument for
`substitute_node()` and restores the tests validating the object
identity when using the flag. This flag was originally excluded from
the implementation because the Rust representation of the dag is not
a shared reference with Python space and the flag doesn't really mean
the same thing as there is always a second copy of the data for Python
space now. The implementation here is cheating slighty as we're passed
in the DAG node by reference it relies on that reference to update the
input node at the same time we update the dag. Unlike the previous
Python implementation where we were updating the node in place and the
`inplace` argument was slightly faster because everything was done by
reference. The rust space data is still a compressed copy of the data
we return to Python so the `inplace` flag will be slightly more
inefficient as we need to copy to update the Python space representation
in addition to the rust version.

* Revert needless dict() cast on metadata in dag_to_circuit()

This commit removes an unecessary `dict()` cast on the `dag.metadata`
when setting it on `QuantumCircuit.metadata` in
`qiskit.converters.dag_to_circuit()`. This slipped in at some point
during the development of this PR and it's not clear why, but it isn't
needed so this removes it.

* Add code comment for DAGOpNode.__eq__ parameter checking

This commit adds a small inline code comment to make it clear why we
skip parameter comparisons in DAGOpNode.__eq__ for python ops. It might
not be clear why the value is hard coded to `true` in this case, as this
check is done via Python so we don't need to duplicate it in rust space.

* Raise a ValueError on DAGNode creation with invalid index

This commit adds error checking to the DAGNode constructor to raise a
PyValueError if the input index is not valid (any index < -1).
Previously this would have panicked instead of raising a user catchable
error.

* Use macro argument to set python getter/setter name

This commit updates the function names for `get__node_id` and
`set__node_id` method to use a name that clippy is happy with and
leverage the pyo3 macros to set the python space name correctly instead
of using the implicit naming rules.

* Remove Ord and PartialOrd derives from interner::Index

The Ord and PartialOrd traits were originally added to the Index struct
so they could be used for the sort key in lexicographical topological
sorting. However, that approach was abandonded during the development of
this PR and instead the expanded Qubit and Clbit indices were used
instead. This left the ordering traits as unnecessary on Index and
potentially misleading. This commit just opts to remove them as they're
not needed anymore.

* Fix missing nodes in matplotlib drawer.

Previously, the change in equality for DAGNodes was causing nodes
to clobber eachother in the matplotlib drawer's tracking data
structures when used as keys to maps.

To fix this, we ensure that all nodes have a unique ID across
layers before constructing the matplotlib drawer. They actually
of course _do_ in the original DAG, but we don't really care
what the original IDs are, so we just make them up.

Writing to _node_id on a DAGNode may seem odd, but it exists
in the old Python API (prior to being ported to Rust) and
doesn't actually mutate the DAG at all since DAGNodes are
ephemeral.

* Revert "Update visual mpl circuit drawer references"

With the previous commit the bug in the matplotlib drawer causing the
images to diverge should be fixed. This commit reverts the change to the
reference images as there should be no difference now.

This reverts commit 1e4e6f3862.

* Update visual mpl circuit drawer references for control flow circuits

The earlier commit that "fixed" the drawers corrected the visualization
to match expectations in most cases. However after restoring the
references to what's on main several comparison tests with control flow
in the circuit were still failing. The failure mode looks similar to the
other cases, but across control flow blocks instead of at the circuit
level. This commit temporarily updates the references of these to the
state of what is generated currently to unblock CI. If/when we have a
fix this commit can be reverted.

* Fix edge cases in DAGOpNode.__eq__

This commit fixes a couple of edge cases in DAGOpNode.__eq__ method
around the python interaction for the method. The first is that in
the case where we had python object parameter types for the gates we
weren't comparing them at all. This is fixed so we use python object
equality for the params in this case. Then we were dropping the error
handling in the case of using python for equality, this fixes it to
return the error to users if the equality check fails. Finally a comment
is added to explain the expected use case for `DAGOpNode.__eq__` and why
parameter checking is more strict than elsewhere.

* Remove Param::add() for global phase addition

This commit removes the Param::add() method and instead adds a local
private function to the `dag_circuit` module for doing global phase
addition. Previously the `Param::add()` method was used solely for
adding global phase in `DAGCircuit` and it took some shortcuts knowing
that context. This made the method implementation ill suited as a
general implementation.

* More complete fix for matplotlib drawer.

* Revert "Update visual mpl circuit drawer references for control flow circuits"

This reverts commit 9a6f9536a3.

* Unify rayon versions in workspace

* Remove unused _GLOBAL_NID.

* Use global monotonic ID counter for ids in drawer

The fundamental issue with matplotlib visualizations of control flow is
that locally in the control flow block the nodes look the same but are
stored in an outer circuit dictionary. If the gates are the same and on
the same qubits and happen to have the same node id inside the different
control flow blocks the drawer would think it's already drawn the node
and skip it incorrectly. The previous fix for this didn't go far enough
because it wasn't accounting for the recursive execution of the drawer
for inner blocks (it also didn't account for LayerSpoolers of the same
length).

* Re-add missing documentation

* Remove unused BitData iterator stuff.

* Make types, dag, and bit count methods public

This commit makes some attributes of the dag circuit public as they will
need to be accessible from the accelerate crate to realistically start
using the DAGCircuit for rust transpiler passes.

* Make Wire pickle serialization explicit

This commit pivots away from using the PyO3 crate's conversion traits
for specialized pickle serialization output of Wire objects. The output
of the previous traits wasn't really intended for representing a Wire in
Python but only for pickle serialization. This commit migrates these to
custom methods, without a trait, to make it clear they're only for
pickle.

* Make py token usage explicit in _VarIndexMap

The _VarIndexMap type was designed to look like an IndexMap but is
actually an inner python dictionary. This is because `Var` types are still
defined in python and we need to use a dictionary if we have `Var`
objects as keys in the mapping. In the interest of looking like an
IndexMap all the methods (except for 1) used `with_gil` internally to
work with the dictionary. This could add unecessary overhead and to make
it explicit that there is python involvement with this struct's methods
this commit adds a py: Python argument to all the methods and removes
the `with_gil` usage.

* Make all pub(crate) visibility pub

* Remove unused method

* Reorganize code structure around PyVariableMapper and BitLocations

* Add missing var wires to .get_wires() method

In the porting of the get_wires() method to Rust the handling of Var
wires was missed in the output of the method. This commit corrects the
oversight and adds them to the output.

* Raise TypeError not ValueError for invalid input to set_global_phase

* De-duplicate check logic for op node adding methods

The methods for checking the input was valid on apply_operation_back,
apply_operation_front, and _apply_op_node_back were all identical. This
combines them into a single method to deduplicate the code.

* Improve collect_1q_runs() filter function

The filter function for collect_1q_runs() was needlessly building a
matrix for all the standard gates when all we need to know in that case
is whether the standard gate is parameterized or not. If it's not then
we're guaranteed to have a matrix available. This commit updates the
filter logic to account for this and improve it's throughput on standard
gates.

* Use swap_remove instead of shift_remove

* Combine input and output maps into single mapping

This commit combines the `DAGCircuit` `qubit_input_map` and
`qubit_output_map` fields into a single `IndexMap` `qubit_io_map` (and
the same for `clbit_input_map` and `clbit_output_map` going to
`clbit_io_map`). That stores the input and output as 2 element array
where the first element is the input node index and the second element
is the output node index. This reduces the number of lookups we need to
do in practice and also reduces the memory overhead of `DAGCircuit`.

* Ensure we account for clbits in depth() short circuit check

* Also account for Vars in DAGCircuit.width()

The number of vars should be included in the return from the width()
method. This was previously missing in the new implementation of this
method.

* Remove duplicated _get_node() method

The `_get_node()` method was duplicated with the already public
`node()` method. This commit removes the duplicate and updates it's only
usage in the code base.

* Handle Var wires in classical_predecessors

This method was missing the handling for var wires, this commit corrects
the oversight.

* Remove stray comment

* Use Operation::control_flow() instead of isinstance checking

* Use &str for increment_op and decrement_op

This commit reworks the interface for the increment_op and decrement_op
methods to work by reference instead of passing owned String objects to
the methods. Using owned String objects was resulting in unecessary
allocations and extra overhead that could be avoided. There are still a
few places we needed to copy strings to ensure we're not mutating things
while we have references to nodes in the dag, typically only in the
decrement/removal case. But this commit reduces the number of String
copies we need to make in the DAGCircuit.

* Also include vars in depth short circuit

* Fix typing for controlflow name lookup in count_ops

* Fix .properties() method to include operations field

The .properties() method should have included the output of .count_ops()
in its dictionary return but this was commented out temporarily while
other pieces of this PR were fixed. This commit circles back to it and
adds the missing field from the output.

As an aside we should probably deprecate the .properties() method for
removal in 2.0 it doesn't seem to be the most useful method in practice.

* Add missing Var wire handling to py_nodes_on_wire

* Add back optimization to avoid isinstance in op_nodes

This commit adds back an optimization to the op_nodes dag method to
avoid doing a python space op comparison when we're filtering on
non-standard gates and evaluating a standard gate. In these cases we
know that the filter will not match purely from rust without needing a
python space op object creation or an isinstance call so we can avoid
the overhead of doing that.

* Simplify/deduplicate __eq__ method

This commit reworks the logic in the DAGCircuit.__eq__ method
implementation to simplify the code a bit and make it less verbose and
duplicated.

* Invalidate cached py op when needed in substitute_node_with_dag

This commit fixes a potential issue in substitute_node_with_dag() when
the propagate_condition flag was set we were not invalidating cached py
ops when adding a new condition based on a propagated condition. This
could potentially cause the incorrect object to be returned to Python
after calling this method. This fixes the issues by clearing the cached
node so that when returning the op to python we are regenerating the
python object.

* Copy-editing suggestions for release notes

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

* Fix and simplify separable_circuits()

This commit fixes and simplifies the separable_circuits() method. At
it's core the method is building a subgraph of the original dag for each
weakly connected component in the dag with a little bit of extra
tracking to make sure the graph is a valid DAGCircuit. Instead of trying
to do this manually this commit updates the method implementation to
leverage the tools petgraph gives us for filtering graphs. This both
fixes a bug identified in review but also simplifies the code.

* Add clbit removal test

* Move to using a Vec<[NodeIndex; 2]> for io maps

This commit migrates the qubit_io_map and clbit_io_map to go from a type
of `IndexMap<Qubit, [NodeIndex; 2], RandomState>` to
`Vec<[NodeIndex; 2]>`. Our qubit indices (represented by the `Qubit`
type) must be a contiguous set for the circuit to be valid, and using an
`IndexMap` for these mappings of bit to input and output nodes only
really improved performance in the removal case, but at the cost of
additional runtime overhead for accessing the data. Since removals are
rare and also inefficient because it needs to reindex the entire dag
already we should instead optimize for the accessing the data. Since we
have contiguous indices using a Vec is a natural structure to represent
this mapping.

* Make add_clbits() signature the same as add_qubits()

At some point during the development of this PR the function signatures
between `add_qubits()` and `add_clbits()` diverged between taking a
`Vec<Bound<PyAny>>` and `&Bound<PySequence>`. In general they're are
comprable but since we are going to be working with a `Vec<>` in the
function body this is a better choice to let PyO3 worry about the
conversion for us. Additionally, this is a more natural signature for
rust consumption. This commit just updates `add_clbits()` to use a Vec
too.

* Add attribution comment to num_tensor_factors() method

* Add py argument to add_declared_var()

* Remove unnecessarily Python-space check

* Correct typo in `to_pickle` method

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Raynel Sanchez <87539502+raynelfss@users.noreply.github.com>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>
Co-authored-by: Eli Arbel <46826214+eliarbel@users.noreply.github.com>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2024-08-23 16:40:59 +00:00
Elena Peña Tapia a4bf87bf66
Fix Rust-space `TwoQubitBasisDecomposer` for non-standard KAK gate (#13014)
* Get rid of encoded assumption in TwoQubitBasisDecomposer that the given KAK gate is a Rust-space StandardGate

* Improve unit test

* Update test/python/synthesis/test_synthesis.py

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2024-08-23 16:31:24 +00:00
Elena Peña Tapia 6b6efc7d54
Filter aer warnings in deprecated `FakeBackend` V1 class (#13018)
* Filter aer warnings in fake backend for the deprecated V1 path

* Filter warnings in QiskitTestCase instead of catching them
2024-08-23 11:04:35 +00:00
Alexander Ivrii 072548ff09
Adding MCX synthesis plugins (#12961)
* moving high-level-synthesis plugins to a separate file

* Adding the remaining MCX synthesis functions and exposting all of them as HLS synthesis plugins.

* adding entry points for MCX plugins

* adding documentation section for MCX plugins

* renaming file

* Adding pending deprecation warnings

* placeholder for MCX plugin tests

* adding flag pending=True to deprecate

* changing checks from isinstance to name-based: a CCCX gate is called mcx but is not an MCXGate

* futher exposing C3X and C4X synthesis

* updating MCX synthesis functions to avoid returning C3X and C4X gates

For better or for worse, C3X and C4X gates have name 'mcx', and
therefore are caught by mcx plugins. We need to avoid recursion
with HLS calling an MCX-synthesis plugin for a C3X-gate, which
in turns returns a C3X-gate.

* fix compose to append

* renaming synthesized circuits for c3x and for c4x back to 'mcx' to avoid qasm changes

* test qasm fixes

* randomly spotted typo

* fixing how QuantumCircuit.decompose works in the presence of gates_to_decompose

* updating MCX plugins to check isinstance

* fixing test

* pylint fixes

* properly fixing test

* additional tests

* adding new synthesis functions to synthesis docs

* release notes

* docstrings improvements followin review

* Adding refernce to Vale et al paper for the MCXPhase gate implementation

* fixes to deprecation warnings and adding deprecation for get_num_ancilla_qubits

* docstring fixes

* renaming mcphase to v24

* removing unncessary checks

* addressing the rest of review comments

* and of course updating qasm checking after we've slightly changed the decomposition

* yet another renaming

* Update qiskit/circuit/library/standard_gates/x.py

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

* Update qiskit/circuit/library/standard_gates/x.py

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

* Update releasenotes/notes/add-mcx-plugins-85e5b248692a36db.yaml

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

* release notes

* formatting

* fixing docs

* removing references from the first sentence of plugin descriptions

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2024-08-22 10:06:09 +00:00
Alexander Ivrii fb81116adc
Operator equality with (clean) ancillas (#12968)
* initial commit

* making the function private; also adding ignore_phase arg

* applying review suggestions
2024-08-22 07:53:50 +00:00
Shravan Patel 6107799ce1
Extended the `from_backend` method of `InstructionDurations` to support both `BackendV1` and `BackendV2` (#12941)
* Extended the `from_backend` method of `InstructionDurations` to support `GenericBackendV2`

* Simplified the `from_backend` method to allow using `BackendV2`. Added a test and a releasenote.

* Made changes to the releasenote.
2024-08-21 09:31:03 +00:00
Shelly Garion aa09a027be
Fix Initialize.gates_to_uncompute method (#12976)
* add back files needed in Initialize.gates_to_uncompute()

* add a test for Initialize.gates_to_uncompute() method

* fix a comment

* add release notes

* update gates_to_uncompute such that it will call Isometry

* remove unused imports

* transfer code from StatePreparation to Initialize.gates_to_uncompute

* update code following review
2024-08-20 13:13:37 +00:00
QuantumDan d430e586f7
Deprecates `StochasticSwap` and suggests the use of `SabreSwap` (#12983)
* first attempt to fix issue 12552

* first attempt to fix issue 12552

* fixed issue 12552 and unittest

* formatted and completed 12552

* formatted and completed 12552 documentation

* fixed unit tests 12552

* Update qiskit/transpiler/passes/routing/stochastic_swap.py

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>

* linted

* passed all tests, including compiler test

* final linting and unittest passing - hopefully

* Update qiskit/transpiler/passes/routing/stochastic_swap.py

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>

* Update releasenotes/notes/deprecate-StochasticSwap-451f46b273602b7b.yaml

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>

* added test

* Apply suggestions from code review

---------

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-08-20 12:28:54 +00:00
jschuhmac 5c8edd4040
Parsing of `seed_transpiler` in `generate_preset_pass_manager` (#12980)
* Raise ValueError if seed_transpiler is negative

* Fix code formatting

* Implement suggested changes

* Update releasenotes/notes/fix-negative-seed-pm-2813a62a020da115.yaml

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>

* Update qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>

---------

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-08-20 08:56:12 +00:00
Julien Gacon 5963027267
fix stateprep's normalize (#12988) 2024-08-19 17:39:35 +00:00
Luciano Bello 713ab38ccc
Internally importing `qiskit.providers.backend.Backend` should not raise `DeprecationWarning` (#12906)
* better module deprecation

* _pulse_library

* __getattr__

* copy qiskit.qobj.PulseQobjInstruction and qiskit.qobj.PulseLibraryItem for internal generic_backend_v2 usage

* lint

* Aer models

* skip

* more generic catch

* specific imports
2024-08-15 17:34:50 +00:00
aeddins-ibm 8c74a49dcd
Fix setter so that `SparsePauliOp.paulis.phase` stays zero (#12884)
* absorb `phase` into `coeffs` in `paulis()` setter

* do not mutate input array

* add test that paulis setter absorbs phase

* lint

* If input paulis have phase, mutate and warn

* add release note

* release-note formatting

* add test with `simplify()`

* remove phase-warning from paulis setter

* lint

* remove unused import

* update reno
2024-08-15 07:42:41 +00:00
Julien Gacon 11e769f30d
Auxiliary qubit tracking in ``HighLevelSynthesis`` (#12911)
* Ancilla tracking for HLS

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

* rm trailing print

* fix round 1 of review comments

* Sasha's review comments

* fix type hint, improve comments

---------

Co-authored-by: AlexanderIvrii <alexi@il.ibm.com>
2024-08-14 11:52:08 +00:00
Julien Gacon 9252713e59
Fix error message upon misalignment in `PadDynamicalDecoupling` (#12952)
* Fix misalignment msg

* slightly better formatting

* typo
2024-08-14 10:14:10 +00:00
Jake Lishman fb9c0dbf89
Improve error message on bad OpenQASM 3 `basis_gates` argument (#12945)
If the user requests a basis-gate name that cannot be used (like a
keyword), there is nothing sensible we can output for a circuit that
contains one of those operations.  The exporter was already correctly
erroring in these cases, but the error message was quite opaque.
2024-08-12 14:11:12 +00:00
Shelly Garion c7e7016419
Move mcx synthesis methods with ancillas to the synthesis library (#12904)
* move mcx synthesis method with dirty ancillas to the synthesis library

* minor lint updates

* move mcx synthesis method with several clean ancillas to the synthesis library

* move handling up to 3 controls to the synthesis code

* move handling up to 3 controls to the synthesis code

* handle cyclic imports

* add mcx synthesis method with one clean ancilla to the synthesis library

* update input to synth_mcx functions

* refactor test for mcx method modes

* update circuit names. add references

* reduce num_controls in tests

* revert circuit names to old ones

* refactor functions names

* add docstrings

* update year

* add synthesis functions to API docs

* add release notes

* fix docs

* update docs and release notes following review

* update imports following review
2024-08-11 11:09:27 +00:00
Takashi Imamichi e7ee189be8
Expose seed in `Estimator` and `StatevectorEstimator` (#12862)
* Fix Estimator and StatevectorEstimator with reset

* reno

* use rng instead of seed

* update reno and tests

* simplify tests

* apply review comments

* Apply suggestions from code review

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

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Julien Gacon <jules.gacon@googlemail.com>
2024-08-08 12:21:16 +00:00
Matthew Treinish adbe88707c
Fix dag visualization with Var wires (#12848)
* Fix dag visualization with Var wires

This commit fixes the dag visualization for DAGs with classical
variables. The Var type was not handled in the attribute callback
functions for nodes and edges. This was causing the visualizer to fail
if the dag contained these types. This fixes this by adding explict
handling for the Var types and using the name attribute of the Var
object.

* Add release note and test
2024-08-08 00:35:20 +00:00
Matthew Treinish 70c2f7813c
Remove init peephole optimization discrete basis check (#12898)
* Fix target handling in discrete basis check

In #12727 a check was added to the default init stage's construction to
avoid running 2q gate consolidation in the presence of targets with
only discrete gates. However the way the target was being used in this
check was incorrect. The name for an instruction in the target should be
used as its identifier and then if we need the object representation
that should query the target for that object based on the name. However
the check was doing this backwards getting a list of operation objects
and then using the name contained in the object. This will cause issues
for instructions that use custom names such as when there are tuned
variants or a custom gate instance with a unique name.

While there is some question over whether we need this check as we will
run the consolidate 2q blocks pass as part of the optimization stage
which will have the same effect, this opts to just fix the target usage
for it to minimize the diff. Also while not the explicit goal of this
check it is protecting against some bugs in the consolidate blocks pass
that occur when custom gates are used. So for the short term this check
is retained, but in the future when these bugs in consolidate blocks are
fixed we can revisit whether we want to remove the conditional logic.

* Remove check and fix ConsolidateBlocks bug

This commit pivots this PR branch to just remove the additional logic
around skipping the optimization passes for discrete basis sets. The
value the check was actually providing was not around a discrete basis
set target and instead was to workaround a bug in the consolidate blocks
pass. If a discrete basis set target was used this would still fail
because we will unconditionally call `ConsolidateBlocks` during the
optimization stage. This commit opts to just remove the extra complexity
of the conditional execution of the peephole optimization passes and
instead just fix the underlying bug in `ConsolidateBlocks` and remove
the check.
2024-08-08 00:16:33 +00:00
Jake Lishman 9de81195ae
Allow arbitrary iterables in `assign_parameters` (#12887)
In Qiskit 1.1, it was possible to give any object that was iterable and
had a `__len__` as the binding sequence for `assign_parameters`.  The
move to Rust space inadvertantly limited that to things that fulfilled
the sequence API.  This commit restores the ability to use general
iterables, and removes the need to have a `__len__`.
2024-08-02 13:46:08 +00:00
Sebastian Brandhofer 1214d51150
'Peephole' optimization - or: collecting and optimizing two-qubit blocks - before routing (#12727)
* init

* up

* up

* Update builtin_plugins.py

* Update builtin_plugins.py

* reno

* Update builtin_plugins.py

* Update builtin_plugins.py

* Update peephole-before-routing-c3d184b740bb7a8b.yaml

* neko check

* check neko

* Update builtin_plugins.py

* test neko

* Update builtin_plugins.py

* Update builtin_plugins.py

* Update builtin_plugins.py

* lint

* tests and format

* remove FakeTorino test

* Update peephole-before-routing-c3d184b740bb7a8b.yaml

* Apply suggestions from code review

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

* comments from code review

* fix precision

* up

* up

* update

* up

* .

* cyclic import

* cycl import

* cyl import

* .

* circular import

* .

* lint

* Include new pass in docs

* Fix Split2QUnitaries dag manipulation

This commit fixes the dag handling to do the 1q unitary insertion.
Previously the dag manipulation was being done manually using the
insert_node_on_in_edges() rustworkx method. However as the original node
had 2 incoming edges for each qubit this caused the dag after running
the pass to become corrupted. Each of the new 1q unitary nodes would end
up with 2 incident edges and they would be in a sequence. This would result
in later passes not being able to correctly understand the state of the
circuit correctly. This was causing the unit tests to fail. This commit
fixes this by just using `substitute_node_with_dag()` to handle the
node substition, while doing it manually to avoid the overhead of
checking is probably possible, the case where a unitary is the product
of two 1q gates is not very common so optimizing it isn't super
critical.

* Update releasenotes/notes/peephole-before-routing-c3d184b740bb7a8b.yaml

* stricter check for doing split2q

* Update qiskit/transpiler/preset_passmanagers/builtin_plugins.py

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

* code review

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

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

* new tests

* typo

* lint

* lint

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2024-08-01 13:48:36 +00:00
Jake Lishman a68de4f9ff
Move `QuantumCircuit.assign_parameters` to Rust (#12794)
* Move `QuantumCircuit.assign_parameters` to Rust

This is (as far as I could tell), the last really major performance
regression in our asv suite compared to 1.1.0, so with this commit, we
should be at _not worse_ for important utility-scale benchmarks.

This largely rewrites `ParamTable` (renamed back to `ParameterTable`
because I kept getting confused with `Param`) to have more Rust-friendly
interfaces available, so that `assign_parameters` can then use them.

This represents a 2-3x speedup in `assign_parameters` performance over
1.1.0, when binding simple `Parameter` instances.  Approximately 75% of
the time is now spent in Python-space `Parameter.assign` and
`ParameterExpression.numeric` calls; almost all of this could be removed
were we to move `Parameter` and `ParameterExpression` to have their data
exposed directly to Rust space.  The percentage of time spent in Python
space only increases if the expressions to be bound are actual
`ParameterExpression`s and not just `Parameter`.

Most changes in the test suite are because of the use of internal-only
methods that changed with the new `ParameterTable`.  The only
discrepancy is a bug in `test_pauli_feature_map`, which was trying to
assign using a set.

* Add unit test of parameter insertion

This catches a bug that was present in the parent commit, but this PR
fixes.

* Update crates/circuit/src/imports.rs

* Fix assignment to `AnnotatedOperation`

* Rename `CircuitData::num_params` to match normal terminology

* Fix typos and 🇺🇸

* Fix lint
2024-08-01 10:56:43 +00:00
Julien Gacon f508ac783c
Fix annotated operation is modified during parameter assignment (#12869) 2024-07-31 16:15:31 +00:00