Commit Graph

8854 Commits

Author SHA1 Message Date
Eric Arellano 6d6dce3272
Remove Eric from Rust bot notifications (#12596) 2024-06-18 09:12:04 +00:00
Catherine Lozano 864a2a3c68
Fixed incorrect behavior of scheduling benchmarks (#12524)
* Setting conditional and reset to false as not supported in alap/asap

* removed deprecated test

* removed unused dag
2024-06-17 15:59:02 +00:00
Luciano Bello 0bca3c403b
Remove extra parenthesis in Primitive examples (#12587)
* remove extra parenthesis

* Update qiskit/primitives/__init__.py

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2024-06-17 15:20:58 +00:00
Catherine Lozano 17ab364786
+= depreciated changed to &= (#12515)
* += depreciated

* fixed deprecated += to &= in two_local
2024-06-17 13:52:53 +00:00
Jake Lishman cd2c65d773
Bump version of macOS used on Azure (#12571)
The macOS 11 runners are deprecated pending removal.  While macOS 14 is
available, it's still marked as in preview on Azure, so macOS 13 is the
current "latest" stable version.
2024-06-14 09:32:03 +00:00
dependabot[bot] 81433d5305
Bump pypa/cibuildwheel in the github_actions group across 1 directory (#12568)
Bumps the github_actions group with 1 update in the / directory: [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel).


Updates `pypa/cibuildwheel` from 2.17.0 to 2.19.1
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.17.0...v2.19.1)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github_actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-13 16:20:17 +00:00
Luciano Bello 2d6a5a2bbb
exclude lines from coverage report (#12564)
* exclude lines from coverage

* comments with explanation

* to pyproject from tox
2024-06-13 11:11:26 +00:00
Matthew Treinish f304a4b4f8
Add infrastructure for gates, instruction, and operations in Rust (#12459)
* Add infrastructure for gates, instruction, and operations in Rust

This commit adds a native representation of Gates, Instruction, and
Operations to rust's circuit module. At a high level this works by
either wrapping the Python object in a rust wrapper struct that tracks
metadata about the operations (name, num_qubits, etc) and then for other
details it calls back to Python to get dynamic details like the
definition, matrix, etc. For standard library gates like Swap, CX, H,
etc this replaces the on-circuit representation with a new rust enum
StandardGate. The enum representation is much more efficient and has a
minimal memory footprint (just the enum variant and then any parameters
or other mutable state stored in the circuit instruction). All the gate
properties such as the matrix, definiton, name, etc are statically
defined in rust code based on the enum variant (which represents the
gate).

The use of an enum to represent standard gates does mean a change in
what we store on a CircuitInstruction. To represent a standard gate
fully we need to store the mutable properties of the existing Gate class
on the circuit instruction as the gate by itself doesn't contain this
detail. That means, the parameters, label, unit, duration, and condition
are added to the rust side of circuit instrucion. However no Python side
access methods are added for these as they're internal only to the Rust
code. In Qiskit 2.0 to simplify this storage we'll be able to drop, unit,
duration, and condition from the api leaving only label and parameters.
But for right now we're tracking all of the fields.

To facilitate working with circuits and gates full from rust the
setting the `operation` attribute of a `CircuitInstruction` object now
transltates the python object to an internal rust representation.
For standard gates this translates it to the enum form described earlier,
and for other circuit operations 3 new Rust structs: PyGate,
PyInstruction, and PyOperation are used to wrap the underlying Python
object in a Rust api. These structs cache some commonly accessed static
properties of the operation, such as the name, number of qubits, etc.
However for dynamic pieces, such as the definition or matrix, callback
to python to get a rust representation for those.

Similarly whenever the `operation` attribute is accessed from Python
it converts it back to the normal Python object representation. For
standard gates this involves creating a new instance of a Python object
based on it's internal rust representation. For the wrapper structs a
reference to the wrapped PyObject is returned.

To manage the 4 variants of operation (`StandardGate`, `PyGate`,
`PyInstruction`, and `PyOperation`) a new Rust trait `Operation` is
created that defines a standard interface for getting the properties
of a given circuit operation. This common interface is implemented for
the 4 variants as well as the `OperationType` enum which wraps all 4
(and is used as the type for `CircuitInstruction.operation` in the
rust code.

As everything in the `QuantumCircuit` data model is quite coupled moving
the source of truth for the operations to exist in Rust means that more
of the underlying `QuantumCircuit`'s responsibility has to move to Rust
as well. Primarily this involves the `ParameterTable` which was an
internal class for tracking which instructions in the circuit have a
`ParameterExpression` parameter so that when we go to bind parameters we
can lookup which operations need to be updated with the bind value.
Since the representation of those instructions now lives in Rust and
Python only recieves a ephemeral copy of the instructions the
ParameterTable had to be reimplemented in Rust to track the
instructions. This new parameter table maps the Parameter's uuid (as a
u128) as a unique identifier for each parameter and maps this to a
positional index in the circuit data to the underlying instruction using
that parameter. This is a bit different from the Python parameter table
which was mapping a parameter object to the id of the operation object
using that parmaeter. This also leads to a difference in the binding
mechanics as the parameter assignment was done by reference in the old
model, but now we need to update the entire instruction more explicitly
in rust. Additionally, because the global phase of a circuit can be
parameterized the ownership of global phase is moved from Python into
Rust in this commit as well.

After this commit the only properties of a circuit that are not defined
in Rust for the source of truth are the bits (and vars) of the circuit,
and when creating circuits from rust this is what causes a Python
interaction to still be required.

This commit does not translate the full standard library of gates as
that would make the pull request huge, instead this adds the basic
infrastructure for having a more efficient standard gate representation
on circuits. There will be follow up pull requests to add the missing
gates and round out support in rust.

The goal of this pull request is primarily to add the infrastructure for
representing the full circuit model (and dag model in the future) in
rust. By itself this is not expected to improve runtime performance (if
anything it will probably hurt performance because of extra type
conversions) but it is intended to enable writing native circuit
manipulations in Rust, including transpiler passes without needing
involvement from Python. Longer term this should greatly improve the
runtime performance and reduce the memory overhead of Qiskit. But,
this is just an early step towards that goal, and is more about
unlocking the future capability. The next steps after this commit are
to finish migrating the standard gate library and also update the
`QuantumCircuit` methods to better leverage the more complete rust
representation (which should help offset the performance penalty
introduced by this).

Fixes: #12205

* Fix Python->Rust Param conversion

This commit adds a custom implementation of the FromPyObject trait for
the Param enum. Previously, the Param trait derived it's impl of the
trait, but this logic wasn't perfect. In cases whern a
ParameterExpression was effectively a constant (such as `0 * x`) the
trait's attempt to coerce to a float first would result in those
ParameterExpressions being dropped from the circuit at insertion time.
This was a change in behavior from before having gates in Rust as the
parameters would disappear from the circuit at insertion time instead of
at bind time. This commit fixes this by having a custom impl for
FromPyObject that first tries to figure out if the parameter is a
ParameterExpression (or a QuantumCircuit) by using a Python isinstance()
check, then tries to extract it as a float, and finally stores a
non-parameter object; which is a new variant in the Param enum. This
new variant also lets us simplify the logic around adding gates to the
parameter table as we're able to know ahead of time which gate
parameters are `ParameterExpression`s and which are other objects (and
don't need to be tracked in the parameter table.

Additionally this commit tweaks two tests, the first is
test.python.circuit.library.test_nlocal.TestNLocal.test_parameters_setter
which was adjusted in the previous commit to workaround the bug fixed
by this commit. The second is test.python.circuit.test_parameters which
was testing that a bound ParameterExpression with a value of 0 defaults
to an int which was a side effect of passing an int input to symengine
for the bind value and not part of the api and didn't need to be
checked. This assertion was removed from the test because the rust
representation is only storing f64 values for the numeric parameters
and it is never an int after binding from the Python perspective it
isn't any different to have float(0) and int(0) unless you explicit
isinstance check like the test previously was.

* Fix qasm3 exporter for std gates without stdgates.inc

This commit fixes the handling of standard gates in Qiskit when the user
specifies excluding the use of the stdgates.inc file from the exported
qasm. Previously the object id of the standard gates were used to
maintain a lookup table of the global definitions for all the standard
gates explicitly in the file. However, the rust refactor means that
every time the exporter accesses `circuit.data[x].operation` a new
instance is returned. This means that on subsequent lookups for the
definition the gate definitions are never found. To correct this issue
this commit adds to the lookup table a fallback of the gate name +
parameters to do the lookup for. This should be unique for any standard
gate and not interfere with the previous logic that's still in place and
functional for other custom gate definitions.

While this fixes the logic in the exporter the test is still failing
because the test is asserting the object ids are the same in the qasm3
file, which isn't the case anymore. The test will be updated in a
subsequent commit to validate the qasm3 file is correct without using
a hardcoded object id.

* Fix base scheduler analysis pass duration setting

When ALAPScheduleAnalysis and ASAPScheduleAnalysis were setting the
duration of a gate they were doing `node.op.duration = duration` this
wasn't always working because if `node.op` was a standard gate it
returned a new Python object created from the underlying rust
representation. This commit fixes the passes so that they modify the
duration and then explicit set the operation to update it's rust
representation.

* Fix python lint

* Fix last failing qasm3 test for std gates without stdgates.inc

While the logic for the qasm3 exporter was fixed
in commit a6e69ba4c9 to handle the edge
case of a user specifying that the qasm exporter does not use the
stdgates.inc include file in the output, but also has qiskit's standard
gates in their circuit being exported. The one unit test to provide
coverage for that scenario was not passing because when an id was used
for the gate definitions in the qasm3 file it was being referenced
against a temporary created by accessing a standard gate from the
circuit and the ids weren't the same so the reference string didn't
match what the exporter generated. This commit fixes this by changing
the test to not do an exact string comparison, but instead a line by
line comparison that either does exact equality check or a regex search
for the expected line and the ids are checked as being any 15 character
integer.

* Remove superfluous comment

* Cache imported classes with GILOnceCell

* Remove unused python variables

* Add missing file

* Update QuantumCircuit gate methods to bypass Python object

This commit updates the QuantumCircuit gate methods which add a given
gate to the circuit to bypass the python gate object creation and
directly insert a rust representation of the gate. This avoids a
conversion in the rust side of the code. While in practice this is just
the Python side object creation and a getattr for the rust code to
determine it's a standard gate that we're skipping. This may add up over
time if there are a lot of gates being created by the method.

To accomplish this the rust code handling the mapping of rust
StandardGate variants to the Python classes that represent those gates
needed to be updated as well. By bypassing the python object creation
we need a fallback to populate the gate class for when a user access the
operation object from Python. Previously this mapping was only being
populated at insertion time and if we never insert the python object
(for a circuit created only via the methods) then we need a way to find
what the gate class is. A static lookup table of import paths and class names
are added to `qiskit_circuit::imports` module to faciliate this and
helper functions are added to facilitate interacting with the class
objects that represent each gate.

* Deduplicate gate matrix definitions

* Fix lint

* Attempt to fix qasm3 test failure

* Add compile time option to cache py gate returns for rust std gates

This commit adds a new rust crate feature flag for the qiskit-circuits
and qiskit-pyext that enables caching the output from
CircuitInstruction.operation to python space. Previously, for memory
efficiency we were reconstructing the python object on demand for every
access. This was to avoid carrying around an extra pointer and keeping
the ephemeral python object around longer term if it's only needed once.
But right now nothing is directly using the rust representation yet and
everything is accessing via the python interface, so recreating gate
objects on the fly has a huge performance penalty. To avoid that this
adds caching by default as a temporary solution to avoid this until we
have more usage of the rust representation of gates.

There is an inherent tension between an optimal rust representation
and something that is performant for Python access and there isn't a
clear cut answer on which one is better to optimize for. A build time
feature lets the user pick, if what we settle on for the default doesn't
agree with their priorities or use case. Personally I'd like to see us
disable the caching longer term (hopefully before releasing this
functionality), but that's dependent on a sufficent level of usage from
rust superseding the current Python space usage in the core of Qiskit.

* Add num_nonlocal_gates implementation in rust

This commit adds a native rust implementation to rust for the
num_nonlocal_gates method on QuantumCircuit. Now that we have a rust
representation of gates it is potentially faster to do the count because
the iteration and filtering is done rust side.

* Performance tuning circuit construction

This commit fixes some performance issues with the addition of standard
gates to a circuit. To workaround potential reference cycles in Python
when calling rust we need to check the parameters of the operation. This
was causing our fast path for standard gates to access the `operation`
attribute to get the parameters. This causes the gate to be eagerly
constructed on the getter. However, the reference cycle case can only
happen in situations without a standard gate, and the fast path for
adding standard gates directly won't need to run this so a skip is added
if we're adding a standard gate.

* Add back validation of parameters on gate methods

In the previous commit a side effect of the accidental eager operation
creation was that the parameter input for gates were being validated by
that. By fixing that in the previous commit the validation of input
parameters on the circuit methods was broken. This commit fixes that
oversight and adds back the validation.

* Skip validation on gate creation from rust

* Offload operation copying to rust

This commit fixes a performance regression in the
`QuantumCircuit.copy()` method which was previously using Python to copy
the operations which had extra overhead to go from rust to python and
vice versa. This moves that logic to exist in rust and improve the copy
performance.

* Fix lint

* Perform deepcopy in rust

This commit moves the deepcopy handling to occur solely in Rust.
Previously each instruction would be directly deepcopied by iterating
over the circuit data. However, we can do this rust side now and doing
this is more efficient because while we need to rely on Python to run a
deepcopy we can skip it for the Rust standard gates and rely on Rust to
copy those gates.

* Fix QuantumCircuit.compose() performance regression

This commit fixes a performance regression in the compose() method. This
was caused by the checking for classical conditions in the method
requiring eagerly converting all standard gates to a Python object. This
changes the logic to do this only if we know we have a condition (which
we can determine Python side now).

* Fix map_ops test case with no caching case

* Fix typos in docs

This commit fixes several docs typos that were caught during code review.

Co-authored-by: Eli Arbel <46826214+eliarbel@users.noreply.github.com>

* Shrink memory usage for extra mutable instruction state

This commit changes how we store the extra mutable instruction state
(condition, duration, unit, and label) for each `CircuitInstruction`
and `PackedInstruction` in the circuit. Previously it was all stored
as separate `Option<T>` fields on the struct, which required at least
a pointer's width for each field which was wasted space the majority of
the time as using these fields are not common. To optimize the memory
layout of the struct this moves these attributes to a new struct which
is put in an `Option<Box<_>>` which reduces it from 4 pointer widths
down to 1 per object. This comes from extra runtime cost from the extra
layer of pointer indirection but as this is the uncommon path this
tradeoff is fine.

* Remove Option<> from params field in CircuitInstruction

This commit removes the Option<> from the params field in
CircuitInstruction. There is no real distinction between an empty vec
and None in this case, so the option just added another layer in the API
that we didn't need to deal with. Also depending on the memory alignment
using an Option<T> might have ended up in a little extra memory usage
too, so removing it removes that potential source of overhead.

* Eagerly construct rust python wrappers in .append()

This commit updates the Python code in QuantumCircuit.append() method
to eagerly construct the rust wrapper objects for python defined circuit
operations.

* Simplify code around handling python errors in rust

* Revert "Skip validation on gate creation from rust"

This reverts commit 2f81bde8bf. The
validation skipping was unsound in some cases and could lead to invalid
circuit being generated. If we end up needing this as an optimization we
can remove this in the future in a follow-up PR that explores this in
isolation.

* Temporarily use git for qasm3 import

In Qiskit/qiskit-qasm3-import#34 the issue we're hitting caused by
qiskit-qasm3-import using the private circuit attributes removed in this
PR was fixed. This commit temporarily moves to installing it from git so
we can fully run CI. When qiskit-qasm3-import is released we should
revert this commit.

* Fix lint

* Fix lint for real (we really need to use a py312 compatible version of pylint)

* Fix test failure caused by incorrect lint fix

* Relax trait-method typing requirements

* Encapsulate `GILOnceCell` initialisers to local logic

* Simplify Interface for building circuit of standard gates in rust

* Simplify complex64 creation in gate_matrix.rs

This just switches Complex64::new(re, im) to be c64(re, im) to reduce
the amount of typing. c64 needs to be defined inplace so it can be a
const fn.

* Simplify initialization of array of elements that are not Copy (#28)

* Simplify initialization of array of elements that are not Copy

* Only generate array when necessary

* Fix doc typos

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

* Add conversion trait for OperationType -> OperationInput and simplify CircuitInstruction::replace()

* Use destructuring for operation_type_to_py extra attr handling

* Simplify trait bounds for map_indices()

The map_indices() method previously specified both Iterator and
ExactSizeIterator for it's trait bounds, but Iterator is a supertrait of
ExactSizeIterator and we don't need to explicitly list both. This commit
removes the duplicate trait bound.

* Make Qubit and Clbit newtype member public

As we start to use Qubit and Clbit for creating circuits from accelerate
and other crates in the Qiskit workspace we need to be able to create
instances of them. However, the newtype member BitType was not public
which prevented creating new Qubits. This commit fixes this by making it
public.

* Use snakecase for gate matrix names

* Remove pointless underscore prefix

* Use downcast instead of bound

* Rwork _append reference cycle handling

This commit reworks the multiple borrow handling in the _append() method
to leveraging `Bound.try_borrow()` to return a consistent error message
if we're unable to borrow a CircuitInstruction in the rust code meaning
there is a cyclical reference in the code. Previously we tried to detect
this cycle up-front which added significant overhead for a corner case.

* Make CircuitData.global_phase_param_index a class attr

* Use &[Param] instead of &SmallVec<..> for operation_type_and_data_to_py

* Have get_params_unsorted return a set

* Use lookup table for static property methods of StandardGate

* Use PyTuple::empty_bound()

* Fix lint

* Add missing test method docstring

* Reuse allocations in parameter table update

* Remove unnecessary global phase zeroing

* Move manually set params to a separate function

* Fix release note typo

* Use constant for global-phase index

* Switch requirement to release version

---------

Co-authored-by: Eli Arbel <46826214+eliarbel@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Kevin Hartman <kevin@hart.mn>
2024-06-13 10:48:40 +00:00
Luciano Bello 439de04e88
Fix the possibly-used-before-assignment in pylint (#12542)
* fix the possibly-used-before-assignment in pylint

* qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py

* test.python.quantum_info.operators.test_utils

* Apply suggestions from code review

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

* https://github.com/Qiskit/qiskit/pull/12542/files#r1636214044

* RuntimeError

* RuntimeError

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2024-06-13 10:47:34 +00:00
Jim Garrison 8a1bcc2d52
Do not retain and expose old elements of `ParameterVector` (#12561)
* Do not retain and expose old elements of `ParameterVector`

This fixes #12541 according to
https://github.com/Qiskit/qiskit/pull/12545#pullrequestreview-2114202382.

* Fix test
2024-06-13 08:18:43 +00:00
Luciano Bello 8d2144cec3
small doc improvements (#12553)
* small doc improvements

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

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

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2024-06-12 13:02:12 +00:00
Jim Garrison 287e86ce8a
Use relative import for `_accelerate` (#12546)
* Use relative import for `_accelerate`

* Fix black

* Disable wrong-import-order in `__init__.py`
2024-06-12 09:32:36 +00:00
Luciano Bello b933f6d377
Add option to user config to control `idle_wires` in circuit drawer (#12462)
* Add option to user config to control idle_wires in circuit drawer

Co-Authored-By: diemilio <diemilio@live.com>

* docs

* 11339

* Update qiskit/visualization/circuit/circuit_visualization.py

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

---------

Co-authored-by: diemilio <diemilio@live.com>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-06-12 09:14:48 +00:00
Will Shanks bc685d3002
Use hash of numeric value for bound parameter expressions (#12488)
* Use hash of numeric value for bound parameter expressions

If a `ParameterExpression` has no unbound parameters, the underlying
bound value can be hashed instead of the tuple that accounts for the
symbolic expression. Doing this allows for the `ParameterExpression` to
match the hash for the numeric value it compares equal to.

Closes #12487

* Add release note
2024-06-11 15:58:34 +00:00
Joe Schulte 03d107e1f6
Removing consider-using-enumerate from lint exclusions and updates (#12286)
* removing consider-using-enumerate from lint exclusions and updates

* updating for lint removal of consider-using-enumerate

* adding disable lint comment for consider-using-enumerate

* updating loops for getting the original, ordered list of qubits in passmanager.py

* reverting update and adding disable comment
2024-06-10 20:39:48 +00:00
Joe Schulte b83efff3b4
Moving group of lint rules (#12315)
* Moving the arguments-renamed, no-member, no-value-for-parameter, not-context-manager, unexpected-keyword-arg, unnecessary-dunder-call, unnecessary-lambda-assignment, and unspecified-encoding lint rules

* updates based on PR and moving not-context-manager back to temp disabled

* inline disable no-value-for-parameter lint exception

* "unnecessary-dunder-call" wrongly removed

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2024-06-10 16:27:28 +00:00
S.S d56a93325a
Fix annotation (#12535)
* 🐛 Fix annotation

* 🎨 Format by black
2024-06-10 12:19:42 +00:00
jpacold 1956220509
Move utility functions _inverse_pattern and _get_ordered_swap to Rust (#12327)
* Move utility functions _inverse_pattern and _get_ordered_swap to Rust

* fix formatting and pylint issues

* Changed input type to `PyArrayLike1<i64, AllowTypeChange>`

* Refactor `permutation.rs`, clean up imports, fix coverage error

* fix docstring for `_inverse_pattern`

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

* fix docstring for `_get_ordered_swap`

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

* remove pymodule nesting

* remove explicit `AllowTypeChange`

* Move input validation out of `_inverse_pattern` and `_get_ordered_swap`

---------

Co-authored-by: Raynel Sanchez <87539502+raynelfss@users.noreply.github.com>
2024-06-10 12:00:21 +00:00
Jim Garrison b2c3ffd738
Improve public type annotations for `OneQubitEulerDecomposer` (#12530) 2024-06-10 10:39:18 +00:00
atharva-satpute f4ca3da35e
Fix broken BasisTranslator translation error link (#12533) 2024-06-10 10:03:23 +00:00
Christopher J. Wood 2b847b8e9b
Fix bugs with VF2Layout pass and Qiskit Aer 0.13 (#11585)
* Fix bugs with V2FLayout pass and Qiskit Aer 0.13

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

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

* test

* Update releasenotes/notes/fix-vf2-aer-a7306ce07ea81700.yaml

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

* long lines

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-06-10 08:39:57 +00:00
shravanpatel30 0b1c8bfd18
[unitaryHACK] Controlling the Insertion of Multi-Qubit Gates in the Generation of Random Circuits #12059 (#12483)
* unitaryHACK Controlling the Insertion of Multi-Qubit Gates in the Generation of Random Circuits #12059

* Fixed linting issues

* Fixed long lines and unused variable

* Added requested changes

* Removed unused imports

* Added a test

* Added the stochastic process comment and edited releasenotes

* Update qiskit/circuit/random/utils.py

* lint...

---------

Co-authored-by: Sebastian Brandhofer <148463728+sbrandhsn@users.noreply.github.com>
2024-06-07 13:04:09 +00:00
Jake Lishman d18a74cd45
Fix `QuantumCircuit.depth` with zero-operands and `Expr` nodes (#12429)
This causes `QuantumCircuit.depth` to correctly handle cases where a
circuit instruction has zero operands (such as `GlobalPhaseGate`), and
to treat classical bits and real-time variables used inside `Expr`
conditions as part of the depth calculations.  This is in line with
`DAGCircuit`.

This commit still does not add the same `recurse` argument from
`DAGCircuit.depth`, because the arguments for not adding it to
`QuantumCircuit.depth` at the time still hold; there is no clear meaning
to it for general control flow from a user's perspective, and it was
only added to the `DAGCircuit` methods because there it is more of a
proxy for optimising over all possible inner blocks.
2024-06-07 11:49:18 +00:00
Will Shanks 72f09adf7e
Avoid exception in `Target.has_calibration` for instruction without properties (#12526)
`Target.add_instruction` allows passing `None` in place of an
`InstructionProperties` instance. In this case, there will be no
`_calibration` attribute, so the `getattr` call properties needs to
provide a default value.
2024-06-06 23:29:08 +00:00
Catherine Lozano 90f09dab70
depreciated U3 gate(qc.U3) changed to qc.U (#12514) 2024-06-06 23:28:33 +00:00
Jake Lishman 92e78ef72a
Bump pylint to 3.2.2 (#12520)
* Bump pylint to 3.2.2

This upgrades pylint to a version compatible with Python 3.8 through
3.12, like Qiskit.  There are a couple of false positives (pylint is
incorrect about its `use-yield-from` in the cases it flags), and has
included a couple of new stylistic opinions that are not necessary to
enforce.

The `possibly-used-before-assignment` lint is quite possibly a good one,
but there are far too many instances in the Qiskit codebase right now to
fix, whereas our current version of pylint is preventing us from running
it with Python 3.12.

* Update requirements-dev.txt

Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>

* Remove suppressions fixed in pylint 3.2.3

---------

Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2024-06-06 20:53:46 +00:00
Kevin Hartman d1c8404dca
[DAGCircuit Oxidation] Refactor bit management in `CircuitData` (#12372)
* Checkpoint before rebase.

* Refactor bit management in CircuitData.

* Revert changes not for this PR.

* Add doc comment for InstructionPacker, rename Interner::lookup.

* Add CircuitData::map_* and refactor.

* Fix merge issue.

* CircuitInstruction::new returns Self.

* Use unbind.

* Make bit types pub.

* Fix merge.
2024-06-06 20:29:23 +00:00
Catherine Lozano 1798c3f208
fixing deprecated methods and incorrect dag state (#12513)
* changed dag state for layout_2q and apply_layout to dag before layout in setup

* Removed CX tests using depreciated cx functions

* fixed formatting
2024-06-06 19:23:35 +00:00
Catherine Lozano 778a6b24ba
Removed deprecated bench test (#12522) 2024-06-06 19:20:57 +00:00
Jake Lishman 767bd07330
Implement `__array__` for `qasm2._DefinedGate` (#12119)
* Implement `__array__` for `qasm2._DefinedGate`

Gates defined from OpenQASM 2 should have a well-defined matrix form (up
to global phase) whenever all the constituent parts of the definition
do. This manually makes such a matrix available.

* Fix signature for Numpy 2.0
2024-06-06 14:13:59 +00:00
Matthew Treinish 9f4a474e97
Fix version table in qpy docs (#12512)
The QPY docs included a format version table that matched up the Qiskit
releases to the supported QPY format versions for that release. However,
a typo resulted in it being treated as a comment instead of table this
commit fixes this and a small copy paste error in one of the versions
listed in the table.
2024-06-06 13:36:10 +00:00
John Lapeyre 72ff2cf20e
Implement `num_qubits` and `num_clbits` in Rust (#12495)
* Implement num_qubits and num_clbits in Rust

* QuantumCircuit.num_qubits and num_clbits are twice as fast after
  this PR.
* These are used in several places. For example QuantumCircuit.width()
  is three times faster.
* num_qubits and num_clbits are introduced in circuit_data.rs. These
  functions are called by the corresponding Python methods.
  They are also used in circuit_data.rs itself.

* Add doc strings for rust implemented num_qubits and num_clbits

* Add doc string for `width` in Rust
2024-06-04 18:12:06 +00:00
Pieter Eendebak 797bb28563
Add __pos__ for Parameter (#12496)
* Add __pos__ for ParameterExpression

* docstring

* Update qiskit/circuit/parameterexpression.py

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

* Add release note

* replace 1.0 by 1

* black

* Reword release note

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2024-06-03 23:39:55 +00:00
Quinten Preiß 9d03b4bf61
Update operation.py docs (#12485)
One "add" too much :)
2024-06-01 02:47:39 +00:00
Elena Peña Tapia 61323662a7
Update `transpile()` and `generate_preset_pass_manager` to convert loose input of constraints to a `Target` with `Target.from_configuration()` (#12185)
* Update transpile() to convert BackendV1 inputs to BackendV2 with BackendV2Converter

* Rework use of instruction durations, move logic from transpile function to individual passes.

* Convert loose constraints to target inside transpile. Cover edge cases where num_qubits and/or basis_gates is None.

* Fix basis gates oversights, characterize errors in test_transpiler.py and comment out failing cases (temporary).

* Fix pulse oversights

* Add backend instructions to name mapping by default

* Fix edge case 3: Add control flow to default basis gates

* Add path for regular cases and path for edge cases that skips target construction.

* Complete edge case handling, fix tests.

* Update reno

* Apply suggestion from Ray's code review

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

* * Migrate full target-building capabilities from transpile to generate_preset_pass_manager.

* Apply Matt's suggestions for custom mapping and control flow op names.

* Extend docstring, fix typos.

* Fix lint, update reno

* Create new reno for 1.2 instead of modifying the 1.1 one.

---------

Co-authored-by: Raynel Sanchez <87539502+raynelfss@users.noreply.github.com>
2024-05-31 12:43:10 +00:00
Joe Schulte df379876ba
Removing _name attribute from Parameter (#12191)
* removing _name attribute from Parameter

* lint fix for parameter update

* fix the __getstate__ structure
2024-05-29 17:27:54 +00:00
dependabot[bot] 473c3c2e58
Bump faer from 0.18.2 to 0.19.0 (#12466)
* Bump faer from 0.18.2 to 0.19.0

Bumps [faer](https://github.com/sarah-ek/faer-rs) from 0.18.2 to 0.19.0.
- [Changelog](https://github.com/sarah-ek/faer-rs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sarah-ek/faer-rs/commits)

---
updated-dependencies:
- dependency-name: faer
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* Bump faer-ext to 0.2.0 too

The faer and faer-ext versions need to be kept in sync. This commit
bumps the faer-ext version as part of the dependabot automated bump for
faer to do this.

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2024-05-28 18:12:33 +00:00
Shelly Garion 0f0a6347d0
Fix a bug in isometry.rs (#12469)
* remove assertion

* extend the test

* add release notes

* fix release notes

* Update releasenotes/notes/fix-isometry-rust-adf0eed09c6611f1.yaml

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2024-05-28 17:59:38 +00:00
Matthew Treinish 529da36fa6
Pin nightly rust version to known working build (#12468)
In the past couple of days we've seen the miri tests fail in CI while
attempting to build crossbeam-epoch from source. We need to do this to
ensure that crossbeam-epoch is miri safe so that we can run our own
tests of Qiskit's unsafe code in ci. This failure was likely an issue in
the recent nightly builds so this commit pins the nightly rust version
to one from last week when everything was known to be working. We can
remove this specific pin when we know that upstream rust has fixed the
issue.
2024-05-28 13:25:07 +00:00
dependabot[bot] 44c0ce3686
Bump pulp from 0.18.12 to 0.18.21 (#12457)
Bumps [pulp](https://github.com/sarah-ek/pulp) from 0.18.12 to 0.18.21.
- [Commits](https://github.com/sarah-ek/pulp/commits)

---
updated-dependencies:
- dependency-name: pulp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-24 12:53:57 +00:00
Matthew Treinish 531f91c24b
Add `DenseLayout` trial to `SabreLayout` (#12453)
Building on the work done in #10829, #10721, and #12104 this commit adds
a new trial to all runs of `SabreLayout` that runs the dense layout
pass. In general the sabre layout algorithm starts from a random layout
and then runs a routing algorithm to permute that layout virtually where
swaps would be inserted to select a layout that would result in fewer
swaps. As was discussed in #10721 and #10829 that random starting point
is often not ideal especially for larger targets where the distance
between qubits can be quite far. Especially when the circuit qubit count
is low relative to the target's qubit count this can result it poor
layouts as the distance between the qubits is too large. In qiskit we
have an existing pass, `DenseLayout`, which tries to find the most
densely connected n qubit subgraph of a connectivity graph. This
algorithm necessarily will select a starting layout where the qubits are
near each other and for those large backends where the random starting
layout doesn't work well this can improve the output quality.

As the overhead of `DenseLayout` is quite low and the core algorithm is
written in rust already this commit adds a default trial that uses
DenseLayout as a starting point on top of the random trials (and any
input starting points). For example if the user specifies to run
SabreLayout with 20 layout trials this will run 20 random trials and
one trial with `DenseLayout` as the starting point. This is all done
directly in the sabre layout rust code for efficiency. The other
difference between the standalone `DenseLayout` pass is that in the
standalone pass a sparse matrix is built and a reverse Cuthill-McKee
permutation is run on the densest subgraph qubits to pick the final
layout. This permutation is skipped because in the case of Sabre's
use of dense layout we're relying on the sabre algorithm to perform
the permutation.

Depends on: #12104
2024-05-22 19:25:32 +00:00
Matthew Treinish f08c579ce1
Expose internal rust interface to DenseLayout (#12104)
* Expose internal rust interface to DenseLayout

This commit makes a small change to the rust code for DenseLayout that
enables calling it more easily from rust. The primary obstacle was the
pyfunction used PyReadonlyArray2<f64> inputs which precludes calling it
with rust constructed Array2Views<f64>. This adds a new inner public
function which takes the array view directly and then the pyfunction's
only job is to convert the inputs and outputs to Python. The python side
of the function is still building a sparse matrix and then runs reverse
Cuthill–McKee to get a permutation of the densest subgraph so any rust
consumers will want to keep that in mind (and maybe use sprs to do the
same).

At the same time it corrects an oversight in the original implementation
where the returned numpy arrays of the densest subgraph are copied
instead of being returned as references. This should slightly improve
performance by eliminating 3 array copies that weren't needed.

* Remove PyResult

---------

Co-authored-by: Henry Zou <87874865+henryzou50@users.noreply.github.com>
2024-05-22 16:31:43 +00:00
Matthew Treinish fc17d60447
Update CITATION.bib file to point to Qiskit whitepaper (#12415)
* Update CITATION.bib file to point to Qiskit whitepaper

This commit updates the official citation for the Qiskit project to
point to the overview paper "Quantum computing with Qiskit" which was
recently published on arxiv:

https://arxiv.org/abs/2405.08810

* Apply suggestions from code review

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
2024-05-22 15:12:23 +00:00
dependabot[bot] 9d0ae64f6d
Bump itertools from 0.12.1 to 0.13.0 (#12427)
Bumps [itertools](https://github.com/rust-itertools/itertools) from 0.12.1 to 0.13.0.
- [Changelog](https://github.com/rust-itertools/itertools/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-itertools/itertools/compare/v0.12.1...v0.13.0)

---
updated-dependencies:
- dependency-name: itertools
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-22 10:51:40 +00:00
Jake Lishman 8e3218bc07
Remove reference to `transpile` from Pulse docs (#12448)
* Remove reference to `transpile` from Pulse docs

This reference to `transpile` was mistakenly inserted as part of 1a027ac
(gh-11565); `execute` used to ignore the `transpile` step for
`Schedule`/`ScheduleBlock` and submit directly to `backend.run`.

I am not clear if there are actually any backends that *accept* pulse
jobs anymore, but if there are, this is what the text should have been
translated to.

* Update qiskit/pulse/builder.py

Co-authored-by: Will Shanks <wshaos@posteo.net>

---------

Co-authored-by: Will Shanks <wshaos@posteo.net>
2024-05-20 18:10:25 +00:00
Arnau Casau 16acb80a03
Remove the duplicated docs for a BackendV1 classmethod (#12443) 2024-05-20 14:04:42 +00:00
Kevin J. Sung 581f24784d
add insert_barrier argument to UnitaryOverlap (#12321)
* add insert_barrier argument to UnitaryOverlap

* set fold=-1 in circuit drawing
2024-05-17 20:49:16 +00:00
Eric Arellano 4e3de44bcb
Add missing paranthesis to pauli_feature_map.py (#12434) 2024-05-17 16:55:48 +00:00
Matthew Treinish 8571afe377
Add merge queue to required tests on github actions (#12428)
This commit adds the missing config to the github actions workflow for
running required tests (currently only arm64 macOS test jobs) to the
merge queue. This is necessary to make the job required in the branch
protection rules, because the jobs will need to pass as part of the
merge queue too.
2024-05-17 12:59:31 +00:00
Arnau Casau 8b569959d0
Fix `qiskit.circuit` method header and broken cross-reference (#12394)
* Fix qiskit.circuit method header

* use object

* fix lint

* Correct method to be defined on `object`

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2024-05-17 00:58:50 +00:00