Commit Graph

8956 Commits

Author SHA1 Message Date
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
Matthew Treinish 8e45a5aad1
Use hashbrown::HashSet instead of ahash::HashSet (#12951)
In the `target_transpiler/mod.rs` module we were using ahash::HashSet
for a hash set implementation, but the rest of Qiskit has standardized
on using hashbrown for the `HashSet` and `HashMap` types. Hashbrown uses
ahash for it's hashing algorithm but it also provides other advantages.
To ensure that hash sets are compatible across the library we should be
using the same library for everything. To support this goal, this commit
also adds a clippy rule that raises a warning if the std library hashmap
or hashset is used, or the versions from ahash. This means with our
current dependency set the only allowed hashset types are
`hashbrown::HashMap`/`HashSet` and `indexmap::IndexMap`/`IndexSet` (for
where we need to maintain insertion order). Ideally we'd have a rule
that forces the use of ahash with `IndexMap` and `IndexSet` (see #12935)
but I don't think clippy exposes an option to enable something like that.
2024-08-13 16:41:26 +00:00
Kevin Hartman 61adcf9d5f
Fix version parsing issue in bloch.py. (#12928) 2024-08-12 17:32:01 +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
Julien Gacon b1e7ffeff0
Allow `CircuitData` construction from `PackedOperation`s (#12943)
* ``CircuitData::from_packed_operations``

* missing import

* remove redundant `to_vec`
2024-08-12 13:42:30 +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
Matthew Treinish 6aa933cc06
Use ahash for IndexMap and IndexSet hasher (#12935)
The ahash hasher offers better performace as a drop in replacement for
the stdlib hash algorithm. This is a large reason we use the hashbrown
crate for our HashMap type in Qiskit (along with rayon support). The
indexmap crate doesn't use ahash by default however, so we typically
switch to it anywhere we use IndexMap or IndexSet to match the lookup
performance of hashbrown in places where we need to preserve insertion
order. However, there were a couple of spots where we missed this in the
rust code, this commit corrects these oversights.
2024-08-09 22:21:29 +00:00
Raynel Sanchez a4f28f2635
Add `get_parameter_by_uuid` to `CircuitData` (#12926)
* Initial: Add `parameter_by_uuid` to `CircuitData`
- This method receives a `uuid` instance from Python and returns the parameter object identified by said `uuid`.

* Fix: Make `get_parameter_by_uuid` a rust only method.
2024-08-09 18:36:17 +00:00
Matthew Treinish 20b51e68b2
Directly construct CircuitData in TwoQubitWeylDecomposition (#12809)
* Directly construct CircuitData in TwoQubitWeylDecomposition

In the recently merged #12740 a path was added for constructing the
`CircuitData` in rust when synthesizing to a `QuantumCircuit`
directly. However, in that PR this was done through a layer of
indirection by first collecting the gates into an intermediate `Vec`
and then passing an iterator of that into
`CircuitData::from_standard_gates()`. However this resulted in an
unecessary allocation for two `Vec`s and it would have been better
to just directly construct the `CircuitData` object directly. However,
to accomplish this we needed more rust space methods for creating
and manipulating a `CircuitData` object as it's mostly being constructed
from Python space or using `CircuitData::from_standard_gates()` with
an iterator so far. This commit makes those additions and then updates
the `TwoQubitWeylDecomposition` code to directly construct the
`CircuitData` object instead of using an intermediate `Vec`.

* Use set_global_phase instead of direct assignment

* Use slice inputs for push_standard_gate() params and qargs
2024-08-08 17:34:53 +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
Jake Lishman 154601ba77
Fix warnings with latest clippy (#12919)
These aren't failing CI, which uses `clippy` at MSRV, they're just
triggered by more recent versions.
2024-08-08 10:08: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 fa5510c3af
Fix short circuit detection for basis translator (#12899)
The BasisTranslator transpiler pass has a check at the very start that
is designed to return fast if there is nothing to translate; in
other words if the instructions in the circuit are already a subset of
instructions supported by the target. This avoid doing a lot of
unecessary work to determine this later during the operation of the
pass. However, this check was not correctly constructed because of a
type mismatch and would only ever get triggered if the input circuit was
empty. The source basis is collected as a `Set[Tuple[str, int]]` where
each tuple is the name and num of qubits for each operation in the
circuit. While the target basis is just a `Set[str]` for the names
supported on the target. This mismatch caused the subset check to never
return True unless it was empty thereby bypassing the intent of the
short circuit path. This commit fixes the logic by constructing a
temporary set of just the source names to evaluate whether we should
return early or not.
2024-08-08 00:18:43 +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
Eric Arellano 1fdd527f90
Update docs links for new URL structure (#12896) 2024-08-02 20:53:09 +00:00
Jim Garrison ebb86b00e3
Add spaces to deprecation warning about `qiskit.providers.models` (#12894) 2024-08-02 17:43:50 +00:00
Jake Lishman 120b73d21d
Avoid exporting incorrect `PyInit_*` symbols (#12889)
Using the `#[pymodule]` derive macro in PyO3 0.21 always causes a
`PyInit_*` symbol with a matching name to be exported in the output
`cdylib`.  This is required for the top-level module, in order for
Python to import it---it needs to know which symbol in a shared library
file it should call---but submodules must be manually initialised, so do
not need it.  Including it is typically harmless (and something we've
been doing for a long time), but it is technically against the coding
rules for CPython extensions[^1].

Recent versions of `abi3audit` (0.0.11+) have tightened their symbol
checkers to better match the CPython guidelines, which causes our wheels
to be rejected by their audits.  This is, in theory, not a break of abi3
because CPython could never introduce an API-elvel `PyInit_*` function
themselves without causing problems, so there ought to be no problems
for our users, even with future Python versions. That said, we still
want to pass the audit, because the coding guidelines are useful.

This commit is not the cleanest way of doing things.  PyO3 0.22 includes
a `#[pymodule(submodule)]` option on the attribute macro, which lets us
use all the standard code generation while suppressing the unnecessary
`PyInit_*` symbol.  When we are ready to move to PyO3 0.22, we probably
want to revert this commit to switch to that form.

[^1]: https://docs.python.org/3/c-api/intro.html
2024-08-02 14:00:31 +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
Matthew Treinish 6663db17a1
Bump macos version in wheels gha workflow (#12882)
During the 1.2.0rc1 release process we had a failure to build the x86_64
macOS jobs. This was because the job was still trying to use the
macos-11 runner which is no longer supported. [1] This commit fixes this
by bumping the version in the wheel job to macos-12.

[1] https://github.blog/changelog/2024-05-20-actions-upcoming-changes-to-github-hosted-macos-runners/
2024-08-02 06:50:05 +00:00
dependabot[bot] 5d534f2c9d
Bump indexmap from 2.2.6 to 2.3.0 (#12877)
Bumps [indexmap](https://github.com/indexmap-rs/indexmap) from 2.2.6 to 2.3.0.
- [Changelog](https://github.com/indexmap-rs/indexmap/blob/master/RELEASES.md)
- [Commits](https://github.com/indexmap-rs/indexmap/compare/2.2.6...2.3.0)

---
updated-dependencies:
- dependency-name: indexmap
  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-08-01 15:01:41 +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 441925e4cf
Speedup the `CommutationChecker` and the `CommutativeCancellation` (#12859)
* Faster commutation checker and analysis

- list of pre-approved gates we know we support commutation on
- less redirections in function calls
- commutation analysis to only trigger search on gates that are actually cancelled

* cleanup comments

* add reno

* review comments

* revert accidentially changed tests

-- these need updating only on the version with parameter support

* revert changes in test_comm_inv_canc

---------

Co-authored-by: MarcDrudis <MarcSanzDrudis@outlook.com>
2024-08-01 09:23:26 +00:00
Jake Lishman 0afb06e8ac
Avoid operator creation in transpiler (#12826)
* Avoid operator creation in transpiler

This removes very nearly all of the use of `DAGOpNode.op` in the default
transpiler paths.  The sole exception is in `InverseCancellation`, which
currently would involve some quite awkward gymnastics for little
near-term benefit. The pass should move fully to Rust soon, making it
not worth the effort.

Most of the tricks here involve using the knowledge that most operations
will involve only Rust-space standard gates, and that these cannot be
control-flow operations.

* Fix `HighLevelSynthesis` fast path

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2024-07-31 18:50:16 +00:00
Elena Peña Tapia 919cfd3baf
Revert base class change for Sampler and Estimator V1 implementations to avoid breaking instance checks. (#12871) 2024-07-31 16:44:35 +00:00
Julien Gacon f508ac783c
Fix annotated operation is modified during parameter assignment (#12869) 2024-07-31 16:15:31 +00:00
dependabot[bot] 4b056a7edf
Bump bytemuck from 1.16.1 to 1.16.3 (#12865)
Bumps [bytemuck](https://github.com/Lokathor/bytemuck) from 1.16.1 to 1.16.3.
- [Changelog](https://github.com/Lokathor/bytemuck/blob/main/changelog.md)
- [Commits](https://github.com/Lokathor/bytemuck/compare/v1.16.1...v1.16.3)

---
updated-dependencies:
- dependency-name: bytemuck
  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-07-31 13:03:23 +00:00
Luciano Bello a6ec8b9ad4
Deprecate BackendV1 and `qiskit.providers.models` (#12629)
* initial commit

* reno

* Apply suggestions from code review

* deprecate qobj and assemble

* reno

* first attempt on Fake1QV2

* deprecate Fake1Q

* Fake1QV2 should not have two-qubit gates

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

* test.python.circuit.test_parameters.TestParameters

* test.python.providers.fake_provider.test_fake_backends.FakeBackendsTest

* test.python.providers.test_fake_backends.TestFakeBackends

* test.python.result.test_mitigators

* test.python.transpiler.test_preset_passmanagers

* test.python.transpiler.test_target

* test.python.transpiler.test_unitary_synthesis

* test.python.transpiler.test_vf2_layout

* test.python.transpiler.test_vf2_post_layout

* test/python/visualization/test_circuit_latex

* test.python.transpiler.test_sabre_layout

* test.python.transpiler.test_sabre_layout

* test.python.transpiler.test_pulse_gate_pass

* test.python.scheduler.test_basic_scheduler.TestBasicSchedule

* test.python.pulse.test_transforms

* test.python.pulse.test_schedule

* test.python.pulse.test_macros

* test.python.pulse.test_instruction_schedule_map

* test.python.pulse.test_block

* test.python.circuit.test_scheduled_circuit

* test.python.transpiler.test_calibrationbuilder

* test.python.providers.test_backendconfiguration

* test.python.compiler.test_transpiler

* test.python.transpiler.test_passmanager_run

* test.python.transpiler.test_passmanager_config.TestPassManagerConfig.test_from_backend_and_user

* test.python.transpiler.test_passmanager_config

* test.python.primitives.test_backend_estimator.TestBackendEstimator

* test.python.circuit.test_scheduled_circuit.TestScheduledCircuit.test_schedule_circuit_when_backend_tells_dt

* test.python.circuit.test_scheduled_circuit

* test.python.transpiler.test_vf2_layout

* shallow deprecation of assemble

* test.python.compiler.test_disassembler

* fakebackend pulse

* test.python.circuit.test_parameters

* PulseQobjInstruction  is used by GenericBackendV2

* test.python.scheduler.test_basic_scheduler

* test.python.result.test_result

* test.python.pulse.test_calibration_entries

* test.python.compiler.test_assembler

* test.python.transpiler.test_star_prerouting

* test.python.pulse.test_instruction_schedule_map

* test.python.providers.basic_provider.test_basic_simulator

* test.python.primitives.test_backend_sampler_v2

* test.python.compiler.test_disassembler

* test.python.compiler.test_compiler

* test.python.circuit.test_scheduled_circuit

* test.python.providers.test_fake_backends

* test.python.circuit.test_unitary

* test.python.transpiler.test_sabre_swap

* test.python.providers.fake_provider.test_fake_backends

* Aer using Provider ABC

* aer warnings

* reno

* another pass on reno

* test.python.pulse

* test.python.compiler.test_compiler

* add module to fiterwarning

* test.python.compiler.test_transpiler

* fixing obscure expcetion handleing for comparison

* test.python.transpiler.test_stochastic_swap test.python.transpiler.test_sabre_swap

* test.python.transpiler.test_echo_rzx_weyl_decomposition

* test.python.transpiler.test_instruction_durations

* test.python.providers.test_backendproperties

* test.python.qpy.test_circuit_load_from_qpy

* test.python.providers.test_pulse_defaults

* test.python.primitives.test_backend_sampler_v2

* test.python.primitives.test_backend_sampler

* test.python.compiler.test_scheduler

* test/python/compiler/test_scheduler.py

* test.python.compiler.test_disassembler

* test.python.compiler.test_assembler

* test.python.compiler.test_sequencer

* test.python.compiler.test_transpiler

* test.python.primitives.test_primitive

* better depreaction handleling from Aer

* test.python.primitives.test_backend_estimator_v2

* test.python.compiler.test_compiler

* ignore warnings, because the output is otherwise very verbose

* ignore to avoid fludding the CI log

* seeding all GenericBackendV2

* test.python.visualization.test_gate_map

* deprecation warnings: once

* default

* default

* BackendConfiguration

* PulseBackendConfiguration

* QasmBackendConfiguration

* QasmBackendConfiguration and adjust stacklevel

* UchannelLO

* GateConfig

* test.python.providers.test_fake_backends.TestFakeBackends

* test.python.providers.test_fake_backends

* test.python.compiler.test_transpiler

* remove catch

* Apply suggestions from code review

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

* remove catch

* new deprecate warning message

* lint qiskit/assembler/assemble_circuits.py

* concurrency warnings

* ignore aer warnings

* Update test/python/providers/fake_provider/test_fake_backends.py

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

* Update test/python/circuit/test_parameters.py

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

* Update qiskit/providers/models/pulsedefaults.py

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

* Update test/python/providers/fake_provider/test_fake_backends.py

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

* Update test/python/providers/fake_provider/test_generic_backend_v2.py

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

* lint

* https://github.com/Qiskit/qiskit/pull/12649#discussion_r1686717954

* https://github.com/Qiskit/qiskit/pull/12649#discussion_r1686717732

* Update test/python/transpiler/test_sabre_swap.py

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

* Update qiskit/providers/models/pulsedefaults.py

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

* ignore Treating CircuitInstruction...

* another unnecessary catch from aer

* another unnecessary catch from aer, again

* removing more unnecesary catches

* less lines

* seeding

* remove those comments

* test.python.compiler.test_transpiler.TestTranspile.test_scheduling_timing_constraints

* tokyo cmap

* test.python.circuit.test_scheduled_circuit.TestScheduledCircuit.test_schedule_circuit_when_backend_tells_dt

* comment in test_sequencer.py

* test.python.compiler.test_transpiler.TestPostTranspileIntegration.test_qasm3_output

* Update test/python/primitives/test_primitive.py

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

* test/python/providers/test_backendconfiguration.py:30

* test.python.primitives.test_backend_sampler

* restore the assertWarns, waiting for #12818

* use legacy_cmaps instead of explict coupling maps

* use more legacy_map

* KYOTO_CMAP

* more legacy_cmap

* https://github.com/Qiskit/qiskit/issues/12832

* test.python.transpiler.test_vf2_post_layout

* comma

* https://github.com/Qiskit/qiskit/pull/12660#discussion_r1694781920

* do not deprecate BackendV2Converter yet

* test.python.providers.test_faulty_backend

* test.python.compiler.test_transpiler.TestTranspile

* cleaning up warnings

* no deprecation in test/python/compiler/test_transpiler.py

* Apply suggestions from code review

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

* reno lint

* adding models in reno

* black

* test.python.transpiler.test_preset_passmanagers

* seeding GenericBackendV2

* less Fake5QV1

* test.python.transpiler.test_sabre_layout

* test.python.transpiler.test_pulse_gate_pass

* test.python.pulse.test_builder

* test.python.primitives.test_backend_sampler_v2

* test.python.primitives.test_backend_sampler_v2

* test.python.primitives.test_backend_estimator_v2

* test.python.compiler.test_transpiler

* Apply suggestions from code review

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

* Apply suggestions from code review

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

* test.python.primitives.test_backend_estimator_v2.TestBackendEstimatorV2

* test.python.primitives.test_backend_estimator_v2

* Fix expected_regex in transpile tests

* Fix missing assertions in:

* test.python.circuit.test_scheduled_circuit

* test.python.compiler.test_sequencer

* test.python.circuit.test_parameters

* test.python.primitives.test_backend_sampler_v2

* test.python.primitives.test_backend_sampler

* Fix line-too-long lint complaints

---------

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
Co-authored-by: Elena Peña Tapia <epenatap@gmail.com>
2024-07-31 10:53:40 +00:00
Raynel Sanchez f9fcd1d0fd
Initial: Make ImportOneCell `new` method public. (#12860) 2024-07-31 10:27:01 +00:00
Matthew Treinish b75c2e093e
Add 100q QV circuit to PGO scripts (#12858)
To get better coverage for PGO, including more examples of two qubit
synthesis, this commit adds a new PGO script to the benchmarks for
running a 100q quantum volume circuit. This provides a different dense
circuit than the other 100q circuits we were running. At the time the
pgo scripts were added this was excluded because it was too slow at the
time. However for the upcoming 1.2 release the transpile time has sped
up a bit so this isn't such a concern anymore as the local transpile
time is now ~2min which seems within the threshold for pgo time.
2024-07-31 07:26:51 +00:00
Takashi Imamichi 68687d3efb
Update metadata of Primitives V2 (#12784)
* update metadata of primitives v2

* remove `shots` and add reno

* add version

* add shots to SamplerV2 metadata

* udpate reno

---------

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-07-30 16:50:26 +00:00
Jake Lishman 43d8372ef7
Expose Sabre heuristic configuration to Python (#12171)
* Expose Sabre heuristic configuration to Python

This exposes the entirety of the configuration of the Sabre heuristic to
Python space, making it modifiable without recompilation.  This includes
some additional configuration options that were not previously easily
modifiable, even with recompilation:

- the base weight of the "basic" component can be adjusted
- the weight of the "basic" and "lookahead" components can be adjusted
  to _either_ use a constant weight (previously not a thing) or use a
  weight that scales with the size of the set (previously the only
  option).
- the "decay" component is now entirely separated from the "lookahead"
  component, so in theory you can now have a decay without a lookahead.

This introduces a tracking `Vec` that stores the scores of _all_ the
swaps encountered, rather than just dynamically keeping hold of the best
swaps.  This has a couple of benefits:

- with the new dynamic structure for heuristics, this is rather more
  efficient because each heuristic component can be calculated in
  separate loops over the swaps, and we don't have to branch within the
  innermost loop.
- it makes it possible in the future to try things like assigning
  probabilities to each swap and randomly choosing from _all_ of them,
  not just the best swaps.  This is something I've actively wanted to
  try for quite some time.

The default heuristics in the transpiler-pass creators for the `basic`,
`lookahead` and `decay` strings are set to represent the same heuristics
as before, and this commit is entirely RNG compatible with its
predecessor (_technically_ for huge problems there's a possiblity that
pulling out some divisions into multiplications by reciprocals will
affect the floating-point maths enough to modify the swap selection).

* Update for PyO3 0.21

* Increase documentation of heuristic components
2024-07-30 14:08:06 +00:00
Matthew Treinish 37b334fb73
Recreate full dag instead of inplace substitution in BasisTranslator (#12195)
* Recreate full dag instead of inplace substitution in BasisTranslator

This commit tweaks the internal logic of the basis translator transpiler
pass to do a full dag recreation instead of inplace modification. If
only a few operations were to be substituted it would probably be more
efficient to do an inplace modification, but in general the basis
translator ends up replacing far more operations than not. In such cases
just iterating over the dag and rebuilding it is more efficient because
the overhead of `apply_operation_back()` is minimal compared to
`substitute_node_with_dag()` (although it's higher than
`subtitute_node(.., inplace=True)`).

* Return boolean together with dag in 'apply_translation' to maintain original 'flow_blocks' logic and fix drawer test.

* Remove print

---------

Co-authored-by: Elena Peña Tapia <epenatap@gmail.com>
2024-07-30 13:50:47 +00:00
Jake Lishman 85f98605a6
Fix parsing of huge OpenQASM 2 conditionals (#12774)
* Fix parsing of huge OpenQASM 2 conditionals

We fixed handling of giant integers in gate expression positions
gh-12140, and this commit fixes the handling in conditionals.
Unfortunately, this means pulling in big-int handling properly; the
integers simply _are_ bigints, and we're not immediately converting them
into something else.

The need to support this may influence how the Rust-space data models of
`QuantumCircuit` evolve.

* Move `num-bigint` dependency to workspace
2024-07-30 13:23:26 +00:00
Takashi Imamichi 239a669ab7
Fix `StatevectorSampler` to raise an error if a circuit with c_if is passed (#12842)
* fix StatevectorSampler with c_if

* add comment
2024-07-30 11:04:51 +00:00
Luciano Bello b985b96b9d
Change the default `routing_method` to `sabre` (#12806)
* change the default routing_method to sabre

* reno

* Update releasenotes/notes/sabre_level0-1524f01965257f3f.yaml

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2024-07-29 17:29:53 +00:00
Henry Zou b23c545233
Port `star_preroute` to rust (#12761)
* This commit ports the core logic of `star_preroute` from Python to Rust. The changes involve creating a new Rust module for the star prerouting algorithm and updating the corresponding Python code to integrate with this new Rust functionality.

Details:
- New Rust file: Added `star_preroute.rs` to handle the core logic of the function `star_preroute` from the python side. This file defines the type aliases for node and block representations, which matches the current block representation of the `StarBlock` (except that the center is just a bool, as we only need to know if there is a center), and the node representation matches how the nodes used in `SabreDAG`. The `star_preroute` function processes the star blocks witihin the `SabreDAG`  and finds the linear routing equivalent and then returns the result as a `SabreResult`. Thus we can use the same methods we used in Sabre, such as `_build_sabre_dag` and `_apply_sabre_result`.
- Node representation: A key part of this implementation is how it takes advantage of `SabreResult` and `SabreDAG`, so the node representation is a tuple of the node id, list of qubit indices, a set of classical bit indices, and a directive flag. However, once we update the regular DAG to rust, this part may change significantly.
- Updates in the SABRE rust module: To use `sabre_dag.rs` and `swap_map.rs` in `star_prerouting`, I change them to be public in `crates/accelerate/src/sabre/mod.rs`. Not sure if it makes more sense to do it this way or to move `star_prerouting` to `crates/accelerate/src/sabre/` since it mimics the methods used in Sabre to change the dag.
- Python side updates: Imported the necessary modules and only modified the function `star_preroute` so that now the function performs the heavy lifting of transforming the DAG within the Rust space, leveraging `_build_sabre_dag` and `_apply_sabre_result`.
- Possible issues: I was not sure how correctly handle control flow from the rust side. I know that `route.rs` handles this with `route_control_flow_block` to populate the `node_block_results` for `SabreResult`, but I was not sure how to best take advantage of this function for `star_prerouting`. Currently, the `node_block_results` for `star_prerouting` essentially always empty and just there to have`SabreResult`. There also seems to be no unit tests for `star_prerouting` that includes control flow.

* lint

* Added additional test and adjust the swap map result

- Added the additional test of qft linearization and that the resultings circuit has `n-2` swap gates where `n` is the number of cp gates.
- Changed the `node_id` in `apply_swap` of `star_preroute.rs` to use the current node id as it is more efficient, but just does not match how we do it in Sabre. This makes it so that we apply the gate first then the swap, which fixes an error we had before where we never placed a swap gate at the end of the processing a block. This only affected tests where we had multiple blocks to process. To make sure we apply the results correctly from `SabreResult`, I added a flag to `_apply_sabre_result` to treat the case of `StarPrerouting` differently so that it applies the swap after applying the node.
- Added a hasp map from node to block to make processing each node in the given processing order have `n + n` time complexity instead of `n^2`. As a result, we can also remove the function `find_block_id`

* Reverted changes to `_apply_sabre_result` and fixed handling on rust side

- Removed `apply_swap_first` flag in `_apply_sabre_result` as it did not make sense to have it as there are no other scenario where a user may want to have control over applying the swap first.
- To adjust for this and make `star_preroute` consistent with `apply_sabre_result` to apply swaps before the node id on the swap map, I adjusted `star_preroute.rs` to first process the blocks to gather the swap locations and the gate order. Once we have the full gate order, we can use the swap locations to apply the swaps while knowing the `qargs` of the node before the swap and the `node_id` of the node after the swap.
- Since the above in done in the main `star_preroute` function, I removed `qubit_ampping` and `out_map` as arguments for `process_blocks`.
2024-07-29 15:14:25 +00:00
Takashi Imamichi bfd2eea480
Make `BitArray.{slice_bits,slice_shots,__getitem__}` raise `IndexError` when indices are not valid (#12755)
* Make BitArray.{slice_bits,slice_shots} raise IndexError when indices are out of bounds

* update __getitem__
2024-07-29 14:10:19 +00:00
Matthew Treinish f8ac2ad22c
Add config option to leverage all cores for sabre (#12780)
* Add config option to leverage all cores for sabre

By default when running sabre in parallel we use a fixed number of
threads (depending on optimization level). This was a tradeoff made for
having deterministic results across multiple systems with a fixed seed
set. However when running qiskit on systems with a lot of CPUs
available we're leaving potential performance on the table by not using
all the available cores. This new flag lets users opt-in to running
sabre with n trials for n CPUs to potentially get better output results
from the transpiler, with minimal to no runtime overhead, at the cost of
the results not necessarily being reproducible when run on a different
computer.

* Apply suggestions from code review

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

* Rework logic to use the default if larger than CPU_COUNT

This commit refactors the logic added in the previous commit to a single
helper function. This reduces the code duplication and makes it easier
to work with. While doing this the logic has been updated so that when
the flag is set and the default number of trials is larger than the
CPU_COUNT we use the default. This means the logic when the flag is set
is to run `max(default_trials, CPU_COUNT)` which should better match
user expectations around the flag.

---------

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-07-29 12:50:08 +00:00
Luciano Bello 7cd2c414b0
Deprecate fake backends based on BackendV1 (#12660)
* deprecate qobj and assemble

* reno

* first attempt on Fake1QV2

* deprecate Fake1Q

* Fake1QV2 should not have two-qubit gates

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

* test.python.circuit.test_parameters.TestParameters

* test.python.providers.fake_provider.test_fake_backends.FakeBackendsTest

* test.python.providers.test_fake_backends.TestFakeBackends

* test.python.result.test_mitigators

* test.python.transpiler.test_preset_passmanagers

* test.python.transpiler.test_target

* test.python.transpiler.test_unitary_synthesis

* test.python.transpiler.test_vf2_layout

* test.python.transpiler.test_vf2_post_layout

* test/python/visualization/test_circuit_latex

* test.python.transpiler.test_sabre_layout

* test.python.transpiler.test_sabre_layout

* test.python.transpiler.test_pulse_gate_pass

* test.python.scheduler.test_basic_scheduler.TestBasicSchedule

* test.python.pulse.test_transforms

* test.python.pulse.test_schedule

* test.python.pulse.test_macros

* test.python.pulse.test_instruction_schedule_map

* test.python.pulse.test_block

* test.python.circuit.test_scheduled_circuit

* test.python.transpiler.test_calibrationbuilder

* test.python.providers.test_backendconfiguration

* test.python.compiler.test_transpiler

* test.python.transpiler.test_passmanager_run

* test.python.transpiler.test_passmanager_config.TestPassManagerConfig.test_from_backend_and_user

* test.python.transpiler.test_passmanager_config

* test.python.primitives.test_backend_estimator.TestBackendEstimator

* test.python.circuit.test_scheduled_circuit.TestScheduledCircuit.test_schedule_circuit_when_backend_tells_dt

* test.python.circuit.test_scheduled_circuit

* test.python.transpiler.test_vf2_layout

* shallow deprecation of assemble

* test.python.compiler.test_disassembler

* fakebackend pulse

* test.python.circuit.test_parameters

* PulseQobjInstruction  is used by GenericBackendV2

* test.python.scheduler.test_basic_scheduler

* test.python.result.test_result

* test.python.pulse.test_calibration_entries

* test.python.compiler.test_assembler

* test.python.transpiler.test_star_prerouting

* test.python.pulse.test_instruction_schedule_map

* test.python.providers.basic_provider.test_basic_simulator

* test.python.primitives.test_backend_sampler_v2

* test.python.compiler.test_disassembler

* test.python.compiler.test_compiler

* test.python.circuit.test_scheduled_circuit

* test.python.providers.test_fake_backends

* test.python.circuit.test_unitary

* test.python.transpiler.test_sabre_swap

* test.python.providers.fake_provider.test_fake_backends

* Aer using Provider ABC

* aer warnings

* reno

* another pass on reno

* test.python.pulse

* test.python.compiler.test_compiler

* add module to fiterwarning

* test.python.compiler.test_transpiler

* fixing obscure expcetion handleing for comparison

* test.python.transpiler.test_stochastic_swap test.python.transpiler.test_sabre_swap

* test.python.transpiler.test_echo_rzx_weyl_decomposition

* test.python.transpiler.test_instruction_durations

* test.python.providers.test_backendproperties

* test.python.qpy.test_circuit_load_from_qpy

* test.python.providers.test_pulse_defaults

* test.python.primitives.test_backend_sampler_v2

* test.python.primitives.test_backend_sampler

* test.python.compiler.test_scheduler

* test/python/compiler/test_scheduler.py

* test.python.compiler.test_disassembler

* test.python.compiler.test_assembler

* test.python.compiler.test_sequencer

* test.python.compiler.test_transpiler

* test.python.primitives.test_primitive

* better depreaction handleling from Aer

* test.python.primitives.test_backend_estimator_v2

* test.python.compiler.test_compiler

* ignore warnings, because the output is otherwise very verbose

* ignore to avoid fludding the CI log

* seeding all GenericBackendV2

* test.python.visualization.test_gate_map

* deprecation warnings: once

* default

* default

* Apply suggestions from code review

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

* remove catch

* new deprecate warning message

* lint qiskit/assembler/assemble_circuits.py

* concurrency warnings

* ignore aer warnings

* Update test/python/providers/fake_provider/test_fake_backends.py

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

* Update test/python/circuit/test_parameters.py

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

* Update qiskit/providers/models/pulsedefaults.py

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

* Update test/python/providers/fake_provider/test_fake_backends.py

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

* Update test/python/providers/fake_provider/test_generic_backend_v2.py

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

* lint

* https://github.com/Qiskit/qiskit/pull/12649#discussion_r1686717954

* https://github.com/Qiskit/qiskit/pull/12649#discussion_r1686717732

* Update test/python/transpiler/test_sabre_swap.py

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

* Update qiskit/providers/models/pulsedefaults.py

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

* ignore Treating CircuitInstruction...

* another unnecessary catch from aer

* another unnecessary catch from aer, again

* removing more unnecesary catches

* less lines

* seeding

* remove those comments

* test.python.compiler.test_transpiler.TestTranspile.test_scheduling_timing_constraints

* tokyo cmap

* test.python.circuit.test_scheduled_circuit.TestScheduledCircuit.test_schedule_circuit_when_backend_tells_dt

* comment in test_sequencer.py

* test.python.compiler.test_transpiler.TestPostTranspileIntegration.test_qasm3_output

* Update test/python/primitives/test_primitive.py

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

* test/python/providers/test_backendconfiguration.py:30

* test.python.primitives.test_backend_sampler

* restore the assertWarns, waiting for #12818

* use legacy_cmaps instead of explict coupling maps

* use more legacy_map

* KYOTO_CMAP

* more legacy_cmap

* https://github.com/Qiskit/qiskit/issues/12832

---------

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-07-29 10:09:40 +00:00
aeddins-ibm 0c03808cd1
Bitarray postselect (#12693)
* define BitArray.postselect()

* add test for BitArray.postselect()

* lint

* remove redundant docstring text

* Update qiskit/primitives/containers/bit_array.py

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

* docstring ticks (BitArray.postselect())

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

* Simpler tests for BitArray.postselect

* lint

* add release note

* check postselect() arg lengths match

* fix postselect tests

- fix bugs with checking that ValueError is raised.
- addtionally run all tests on a "flat" data input

* lint

* Fix type-hint

We immediately check the lengths of these args, so they should be Sequences, not Iterables.

* remove spurious print()

* lint

* lint

* use bitwise operations for faster postselect

- Also added support for negative indices
- Also updated tests

* remove spurious print()

* end final line of release note

* try to fix docstring formatting

* fix bitarray test assertion

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

* disallow postselect positional kwarg

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

* fix numpy dtype args

* Simpler kwarg: "assume_unique"

* lint (line too long)

* simplification: remove assume_unique kwarg

* improve misleading comment

* raise IndexError if indices out of range

- Change ValueError to IndexError.
- Add check for out-of-range negative indices.
- Simplify use of mod
- Update test conditions (include checks for off-by-one errors)

* lint

* add negative-contradiction test

* Update docstring with IndexErrors

* lint

* change slice_bits error from ValueError to IndexError

* update slice_bits test to use IndexError

* change ValueError to IndexError in slice_shots

also update tests for this error

* update error type in slice_shots docstring

* Revert ValueError to IndexError changes

Reverting these changes as they will instead be made in a separate PR.

This reverts commit 8f3217838c.

Revert "update error type in slice_shots docstring"

This reverts commit 50545efbf2.

Revert "change ValueError to IndexError in slice_shots"

This reverts commit c4becd9b0e.

Revert "update slice_bits test to use IndexError"

This reverts commit c2b00390da.

* fix docstring formatting

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

* allow selection to be int instead of bool

* In tests, give selection as type int

* lint

* add example to release note

* fix typo in test case

* add check of test

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

* lint

---------

Co-authored-by: Ian Hincks <ian.hincks@gmail.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
2024-07-29 09:53:43 +00:00
Elena Peña Tapia b7d0a974b6
Primitive V1 deprecation follow-up (#12824)
* Apply tweaks to deprecation messages, docstrings and release notes.

* Fix missing backtick

* Apply suggestions from Luciano's code review

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

* Update qiskit/primitives/statevector_sampler.py

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

* Update qiskit/primitives/backend_sampler.py

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

* Update qiskit/primitives/primitive_job.py

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

* Update qiskit/primitives/base/base_estimator.py

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

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
2024-07-29 09:39:41 +00:00
Jake Lishman b362df0c42
Allow overriding Rust toolchain in `tox` runs (#12827)
It can be convenient to use different versions of the Rust toolchain for
various `tox` runs.  This can already be done externally to `tox`
by a stateful `rustup override set <x>` followed by clearing the
override after the tox run, but allowing the environment variable to
pass through lets it be localised to just a single run.
2024-07-26 21:03:52 +00:00
Matthew Treinish c8c53cc6f8
Add a default optimization level to generate_preset_pass_manager (#12150)
* Add a default optimization level to generate_preset_pass_manager

This commit adds a default value to the generate_preset_pass_manager's
optimization_level argument. If it's not specified optimization level 2
will be used. After #12148 optimization level 2 is a better fit for an
optimal tradeoff between heuristic effort and runtime that makes it
well suited as a default optimization level.

* Update transpile()'s default opt level to match

This commit updates the transpile() function's optimization_level argument
default value to match generate_preset_pass_manager's new default to use 2
instead of 1. This is arguably a breaking API change, but since the
semantics are equivalent with two minor edge cases with implicit behavior
that were a side effect of the level 1 preset pass manager's construction
(which are documented in the release notes) we're ok making it in this
case. Some tests which we're relying on the implicit behavior of
optimization level 1 are updated to explicitly set the optimization
level argument which will retain this behavior.

* Update more tests expecting optimization level 1

* * Set optimization level to 1 in test_approximation_degree.

* Replace use of transpile with specific pass in  HLS tests.

* Set optimization_level=1 in layout-dependent tests.

* Expand upgrade note explanation on benefits of level 2

* Apply Elena's reno suggestions

---------

Co-authored-by: Elena Peña Tapia <epenatap@gmail.com>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-07-26 17:29:21 +00:00
Julien Gacon 1512535a97
Add `AnnotatedOperation.params` and fix some control issues (#12752)
* AnnotatedOp.params support and Gate.control fix

* add reno

* lint

* update reno

* review comments

- use attribute error
- more clearly state the new None arg in reno and Gate class

* review from Elena

* Fix ``AttributeError`` test

* lint

* Apply suggestions from code review

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-07-26 15:55:50 +00:00
Sebastian Brandhofer edf0b53a01
Setting noise_info to false in GenericBackendV2 creates issues later in the transpiler pipeline (#12769)
* up

* fix

* Apply suggestions from code review

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

* lint

---------

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-07-26 12:27:21 +00:00
YingHongTham 4ec51d1a83
fixes #9355 deprecate visualize_transition (#12287)
* added deprecation warnings and decorators to transition_visualization.py

* fixed style with tox -epy310 -eblack

* added release notes

* added to warning category=DeprecationWarning and stacklevel=2

* Update releasenotes/notes/deprecate-visualize_transition-8c1d257b7f37aa58.yaml

Co-authored-by: atharva-satpute <55058959+atharva-satpute@users.noreply.github.com>

* Update releasenotes/notes/deprecate-visualize_transition-8c1d257b7f37aa58.yaml

Co-authored-by: atharva-satpute <55058959+atharva-satpute@users.noreply.github.com>

* Apply suggestions from code review

* Fix lint complaint

---------

Co-authored-by: atharva-satpute <55058959+atharva-satpute@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2024-07-26 12:25:13 +00:00
aeddins-ibm c40ce8327b
Fix `BitArray.from_counts`/`from_samples` to not fail for input with only `0` outcome and `num_bits=None` (#12800)
* interpret `0` as represented by 1 bit

* Test conversion of counts w only `0` outcome

* add release note
2024-07-26 09:09:08 +00:00
Raynel Sanchez 898fdec48a
Adding `Target` and `InstructionProperties` representations to rust (#12292)
* Initial: Add `Target` class to `_accelerate`
- Add `Target` class to test mobility between Rust and Python.
- Add `add_instruction` method to test compatibility with instructions.

* Fix: Remove empty property check
- Property check caused most cases to panic.
- Will be commented out and restored at a later time.

* Add: Instructions property
- Instructions property returns all added to the target.
- Similar behavior to source.

* Chore: comments and deprecated methods
- Add comments to instruction property.
- Use new_bound for new PyDicts.

* Chore: Remove redundant code
- Remove redundant transformation of PyObject to PyTuple.
- Remove debugging print statement.

* Add: `InstructionProperties` class and type checkers
- Add `InstructionProperties` class to process properties in rust.
- Add `is_instance` and `is_class` to identify certain Python objects.
- Modify logic of `add_instruction` to use class check.
- Other tweaks and fixes.

* Add: Setter and Getter for calibration in `InstructionProperty`

* Add: `update_instruction_properties` to Target.

* Add: Update_from_instruction_schedule_map
- Partial addition from Target.py\
- Introduction of hashable qarg data structure.
- Other tweaks and fixes.

* Add: Complete `update_from_instruction_schedule_map1
- Complete missing procedures in function.
- Rename `Qargs` to `HashableVec`.
- Make `HashableVec` generic.
- Separate `import_from_module_call` into call0 and call1.
- Other tweaks and fixes.

* Add: instruction_schedule_map property.
- Remove stray print statements.
- Other tweaks and fixes.

* Fix: Key issue in `update_from_instruction_schedule_map`
- Remove all unsafe unwraps

* Fix: Use PyResult Value for void functon
- Update `update_from_instruction_schedule_map to use PyResult and '?' operator.
- Use Bound Python objects whenever possible.
- Other tweaks and fixes.

* Add: Python wrapping for Target
- Add temporary _target module for testing.
- Remove update_from_instruction_schedule_map function back to python.
- Add python properties for all public attributes in rust
- Other tweaks and fixes.

* Add: `qargs` property
- Add identical method `qargs` to obtain the qargs of a target.
- Other tweaks and fixes.

* Add: `qargs_for_operation_name` function.
- Add function with identical behavior to the original in Target.
- Other tweaks and fixes.

* Add: durations method for Target
- Add target module to qiskit init file.
- Remove is_instance method.
- Modify set_calibration method in InstructionProperty to leave typechecking to Python.
- Change rust Target alias to Target2.
- Other tweaks and fixes,

* Add: InstructionProperties wrapper in python

* Fix: InstructionProperties could not receive calibrations
- Fix wrong setters/getters for calibration in InstructionProperty object in rust.

* Add: more methods to Target in `target.rs`
- Add FromPyObject trait to Hashable vec to receive Tuples and transform them directly into this type.
- Add operations_for_qargs for Target class in Rust side and Python.
- Fix return dict keys for `qargs_for_operation_name`.
- Add `timing_constrains` and `operation_from_name` to Python side.
- Other tweaks and fixes.

* Fix: missing return value in `operations_for_args`
- Fix wrong name for function operation_for_qargs.
- Fix missing return value in the python side.
- Other tweaks and fixes.

* Fix: Bad compatibility with InstructionProperties
- Make `InstructionProperties` "_calibration" attribute visible.
- Removed attribute "calibration", treat as class property.
- Other tweaks and fixes

* Add: `operation_names_for_qargs` to Target
- Port class method to rust and connect to Python wrapper.
- Other tweaks and fixes.

* Add: instruction_supported method to rust and python:
- Other tweaks and fixes.

* Add: changes to add_instruction function to increase functionality.
- These changes break current functionality of other functions, butemulate intended behavior better.
- Fixes coming soon.

* Fix: Backwards compatibility with `add_instruction`
- Fixed wrong additions to HashMaps in the rust side causing instructions to be missing.
- Other tweaks and fixes.

* Fix: Gate Map behavior didn't match #11422
- Make GateMap use optional values to match behavior of #11422.
- Define GateMapType for complex type in self.gate_map.
- Throw Python KeyError exceptions from the rust side in `update_instruction_properties` and other functions.
- Modify logic in subsequent functions that use gate_map optional values.
- Other tweaks and fixes.

* Add: `has_calibration` method to Target

* Add: `get_calibraton` method to Target

* Add: `instruction_properties` method to Target

* Add: `build_coupling_map` and helper methods
- `build_coupling_map`will remain in Python for now, along with its helper functions.
- Make `gate_name_map` visible to python.
- Add `coupling_graph` attribute to Target in Rust.
- Other tweaks and fixes.

* Add: `get_non_global_operation_names` to Target.
- Add attributes `non_global_strict_basis` and `non_global_basis` as Optional.
- Other tweaks and fixes.

* Add: Missing properties
- Add properties: operations, operation_names, and physical_qubits.
- Reorganize properties placement.
- Other tweaks and fixes.

* Add: `from_configuration` classmethod to Target.
- Add method that mimics the behavior of the python method.
- Change concurrent_measurements to 2d Vec instead of a Vec of sets.
- Other tweaks and fixes.

* Add: Magic methods to Rust and Python
- Add docstring to __init__.
- Add __iter__, __getitem__, __len__, __contains__, keys, values, and items methods to rust.
- Add equivalen methods to python + the __str__ method.
- Make description an optional attribute in rust.
- Other tweaks and fixes.

* Fix: Bugs when fetching qargs or operations
- Fix qarg_for_operation_name logic to account for None and throw correct exceptions.
- Stringify description before sending in case of numerical descriptors.
- Fix qarg to account for None entry.
- Other tweaks and fixes.

* Chore: Prepare for Draft PR
- Remove _target.py testing file.
- Fix incorrect initialization of calibration in InstructionProperties.
- Other tweaks and fixes.

* Fix: target not being recognized as a module
- Add target to the pyext crate.
- Change placement of target import for alphabetical ordering.
- Other tweaks and fixes.

* Fix: Change HashMap to IndexMap
- Change from f32 to f64 precision.
- Other tweaks and fixes.

* Fix: Move InstructionProperties fully to Rust
- Move InstructionProperties to rust.
- Modify gate_map to accept an InstructionProprties object instead of PyObjecy.
- Change update_instruction_properties to use Option InstructionProprtyird.
- Remove InstructionProperties from target.py
- Other tweaks and fixes.

* Fix: Make Target inherit from Rust
- Make Target inherit from the rust-side Target by using subclass attribute, then extending its functionality using python.
- Switch from __init__ to __new__ to adapt to the Target rust class.
- Modify every trait that worked with `target._Target` to use `super()` or `self` instead.
- Fix repr in InstructionProperties to not show `Some()` when a value exists.
- Fix `__str__` method in `Target` to not display "None" if no description is given.
- Assume `num_qubits` is the first argument when an integer is provided as a first argument and nothing else is provided for second (Target initializer).
- Return a set in operation_names instead of a Vec.
- Other tweaks and fixes.

* Fix: Recognize None in `operation_for_qargs`.
- Fix module labels for each class in target.rs.
- Use py.is_instance instead of passing isinstance to `instruction_supported`.
- Modify `operations_for_qargs` to accept optional values less aggressively. Allow it to find instructions with no qargs. (NoneType).
- Other tweaks and fixes.

* Fix: Make InstructionProperties subclassable.
- Fix get_non_global_operation_names to accept optional values and fix search set to use sorted values.
- Fix __repr__ method in InstructionProperties to add punctuation.
- Fix typo in python durations method.
- Modify test to overload __new__ method instead of just  __init__ (Possible breaking change).
-Other tweaks and fixes.

* Fix: errors in `instruction_properties` and others:
- Allow `instruction_properties` method to view optional properties.
- Allow `operation_names_for_qargs` to select class instructions when None is passed as a qarg.
- Modify __str__ method to display error and duration times as int if the value is 0.
- Other tweaks and fixes.

* Fix: call `isclass` from rust, instead of passing it from Python.

* Fix: Move `update_from_instruction_schedule_map` to rust.

* Fix: Move `durations` to rust.

* Fix: Move `timing_constraints` to rust

* Fix: Move operations_from_name fully to rust

* Fix: `instruction_supported` method:
- Rewrite the logic of instruction_supported due to previous errors in the method.
- Move `check_obj_params` to Rust.
- Other tweaks and fixes.

* Fix: errors in `from_configuration` class method.
- Fix some of the logic when retrieving gates from `name_mapping`.
- Remove function arguments in favor of implementing counterpart functions in rust.
- Add qubit_props_list_from_props function and return rust datatypes.
- Fix wrong error handling procedures when retrieving attributes from backend_property.
- Other tweaks and fixes.

* Fix: Import `InstructionScheduleMap` directly instead of passing.
- `instruction_schedule_map()` now imports the classtype directly from rust instead of needing it to be passed from python.
- Remove unused imports in `target.py`.
- Ignore unused arguments in `test_extra_props_str`.
- Other tweaks and fixes.

* Docs: Add docstrings to rust functions
- Remove redundant redefinitions in python.
- Fix text_signatures for some rust functions.
- Added lint exceptions to some necessary imports and function arguments.
- Other tweaks and fixes.

* Add: Make `Target` and `InstructionProperties` pickleable.
- Add `__getstate__` and `__setstate__` methods to make both rust subclasses pickleable.

* Fix: Wrong calibration assignment in __setstate__
- Use set_calibration to set the correct calibration argument.
- Fix wrong signature in get_non_global_operation_names.
- Other tweaks and fixes.

* Refactor: HashableVec is now Qarg
- Use `PhysicalQubit` instead of u32 for qargs.
- Use a `SmallVec` of size 4 instead of a dynamic Vec.
- Default to using the `Hash()` method embedded in `SmallVec`.
- Add a Default method to easily unwrap Qarg objects.
- Other tweaks and fixes.

* Add: `get` function to target.
- Remove some redundant cloning in code.
- Other small fixes.

* Fix: Remove unnecessary Optional values in gate_map.
- Update every gate_map call to use the new format.
- Other small tweaks and fixes.

* Refactor: `calibration` is for `InstructionProperties`
- Use python `None` instead of option to store `calibration` in `InstructionProperties`.
- Adapt code to these changes.
- Remove redundant implementation of Hash in Qargs.
- Other tweaks and fixes.

* Fix: Temporary speedup for `gate_map` access
- Added temporary speedups to access the gate_map by returning the values as PyObjects.
- Convert qargs to rust tuples instead of initializing a `PyTuple`.
- Store `InstructionProperties` as a python ref in gate_map. (Will be changed in future updates).
- Other tweaks anf fixes.

* Fix: Incorrect extractions for `InstructionProperties`
- Fix incorrect conversion of `InstructionProperties` to `Py<InstructionProperties>`
- Fix incorrect extraction of qargs in `update_from_instruction_schedule_map`

* Fix: Hide all private attributes in `Target`
- Hide all private attributes of the `Target` to prevent unecessary cloning.
- Other small tweaks and fixes.

* Add: New representation of gate_map using new pyclasses:
- Make Qarg a sequence pyclass.
- Make QargPropsMap the new representation of a GateMap value.
- Adapt the code to new structure.
- TODO: Add missing magic methods for sequence and mapping objects.
- Other small tweaks and fixes.

* Add: Use custom datatypes to return values to Python.
- Add QargSet datatype to return a set of qargs.
   - Works as return type for `Target.qargs`
   - Object is has itertype of QargSetIter.
- Rename QargPropMap to PropsMap
   - Use iterator type IterPropsMap
- Other small tweaks and fixes.

* Fix: Extend `InstructionProperties` to be subclassable using `__init__:
- Made a subclass of `InstructionProperties` that can be extended using an `__init__`method.
- Revert previous changes to `test_target.py`.
- Other tweaks and fixes.

* Refactor: Split target into its own module
- Reestructure the files to improve readability of code.
   - `instruction_properties.rs` contaisn the `InstructionProperties` class.
   - `mod.rs` contains the `Target` class.
   - `qargs.rs` contains the Qargs struct to store quantum arguments.
   - `property_map` contains the Qarg: Property Mapping that will be stored in the gate_map.
- Add missing methods to PropsMap:
   - Add `PropsMapKeys` object to store the qargs as a set.
   - Add methods to compare and access `PropsMapKey`.
- Add QargsOrTuple enum in Qargs to parse Qargs instantly.

* Fix: Rest of failing tests in Target
- Modify the `InstructionProperties` python wrapper.
   - InstructionProperties was not assigning properties to rust side.
- Make duration in `InstructionProperties` setable.
- Add `__eq__` method for `PropMap` to compare with other dicts.
- `PropMapKeys` can only be compared with a Set.
- Remove `qargs_for_operation_name` from `target.py`
- Other small tweaks and fixes.

* Add: New GateMap Structure
- GateMap is now its own mapping object.
- Add `__setstate__` and `__getstate__` methods for `PropMap` and `GateMap`.
- Other small tweaks and fixes.

* Fix: Make new subclasses pickleable
- Add module location to `PropsMap`, `GateMap`, and `Qargs`.
- Added default method to PropMap.
- Made default method part of class initializers.
- Other smalls tweaks and fixes.

* Fix: Remove redundant lookup in Target (#12373)

* Format: `mod.rs` qubit_comparison to one line.

* Add: `GateMapKeys` object in GateMap:
- Use IndexSet as a base to preserve the insertion order.
- Other tweaks and fixes.

* Add: __sub__ method to GateMapKeys

* Fix: Modify `GateMap` to store values in Python heap.
- Fix `GateMap.__iter__` to use an IndexKeys iterator.
- Other small tweaks and fixes.

* Fix: Remove duplicate import of `IndexSet::into_iter` in `GateMap`.
- Make `__iter__` use the keys() method in `GateMap`.

* Fix:: Adapt to target changes (#12288)
- Fix lint stray imports.

* Fix: Incorrect creation of parameters in `update_from_instruction_schedule_map`
- Add `tupelize` function to create tuples from non-downcastable items.
- Fix creation of Parameters by iterating through members of tuple object and mapping them to parameters in `update_from_instruction_schedule_map`.
- Add missing logic for creating a Target with/without `qubit_properties`.
- Add tuple conversion of `Qargs` to store items in a dict in `BasisTranslator` and `UnitarySynthesis` passes.
- Cast `PropsMap` object to dict when comparing in `test_fake_backends.py`.
- Modify logic of helper functions that receive a bound object reference, a second `py` not required as an argument.
- Add set operation methods to `GateMapKeys`.
- Other tweaks and fixes.

* Fix: More failing tests
- Fix repeated erroneous calls to `add_instruction` in `update_from_instruction_schedule_map`
- Add missing condition in `instruction_supported`
- Use `IndexSet` instead of `HashSet` for `QargsSet`.
- Other small tweaks and fixes.

* Add: Macro rules for qargs and other sequences.
- Create `QargSet` and `PropsMap` using the new macros.
- Return a `TargetOpNames` ordered set to python in `operation_names`.
- Remove the Python side `operation_names.`
- Fix faulty docstring in `target.py`.
- Other tweaks and fixes.

* Docs: Add necessary docstrings to all new rust functions.
- Remove duplicate Iterator in GateMap.
- Other small tweaks and fixes.

* Fix: Use `GILOneCell` and remove `Qargs`
- Use `GILOneCell` to import python modules only once at initialization.
- Remove the custom data structure `Qargs` to avoid conversion overhead.
- `Qargs` does not use `PhysicalQubits`, `u32` is used instead.
- Fix `__setstate__ `and `__getstate__` methods for `PropsMap`, `GateMap`, and `key_like_set_iterator` macro_rule.
- Update code to use the new structures.
- TODO: Fix broken tests.

* Fix: Cast `Qargs` to `Tuple` in specific situations
- Use tupleize to cast `Qargs` to `Tuple` in `instructions`.
- Use downcast to extract string in `add_instruction`.
- Other tweaks and fixes.

* Add: Make `Target` Representable in Rust
- Rename `InstructionProperties` as `BaseInstructionProperties`.
   - Remove `Calibration` from the rust space.
- Restore `gate_map`, `coupling_map`, `instruction_schedule_map`, and `instruction_durations` to rust.
- Remove all unnecessary data structures from rust space.
- Other tweaks and fixes.

* Refactor: Remove previour changes to unrelated files.

* Add: rust native functions to target
- Added rust native functionality to target such that a `py` would not be needed to use one.
- Add Index trait to make `Target` subscriptable.
- Other small tweaks and fixes.

* Fix: Remove all unnecessary python method calls.
- Remove uage of `inspect.isclass`.
- Rename `Target` to `BaseTarget` in the rust side.
- Rename `err.rs` to `errors.rs`.
- Remove rust-native `add_inst` and `update_inst` as Target should not be modified from Rust.
- Made `add_instruction` and `update_instruction_properties` private in `BaseTarget`.
- Add missing `get` method in `Target`.
- Other tweaks and fixes

* Format: Fix lint

* Fix: Wrong return value for `BaseTarget.qargs`

* Add: Temporary Instruction representation in rust.
- Add temporary instruction representation to avoid repeated extraction from python.

* Add: Native representation of coupling graph

* Fix: Wrong attribute extraction for `GateRep`

* Remove: `CouplingGraph` rust native representation.
- Move to different PR.

* Format: Remove stray whitespace

* Add: `get_non_global_op_names` as a rust native function

* Fix: Use Ahash for Hashing
- Use ahash for hashing when possible.
- Rename `BaseTarget` to `Target` in rust only.
- Rename `BaseInstructionProperties` to `InstructionProperties` in rust only.
- Remove optional logic from `generate_non_global_op_names`.
- Use dict for `__setstate__` and `__getstate__` in `Target`.
- Reduced the docstring for `Target` and `InstructionProperties`.
- Other small tweaks and fixes.

* Format: new changes to `lib.rs`

* Format: Adapt to new lint rules

* Fix: Use new gates infrastructure (#12459)
- Create custom enum to collect either a `NormalOperation` or a `VariableOperation` depending on what is needed.
- Add a rust native `is_instruction_supported` method to check whether a Target supports a certain instruction.
- Make conversion methods from `circuit_instruction.rs` public.
- Add comparison methods for `Param` in `operations.rs`
- Remove need for isclass method in rustwise `add_instruction`
- Other tweaks and fixes.

* Format: Fix rust formatting

* Add: rust-native method to obtain Operstion objects.

* Add: Comparison methods for `Param`

* FIx: Add display methods for `Params`

* Format: Fix lint test

* Format: Wrong merge conflict solve

* Fix: Improve rust methods to use iterators.
- Adapt the Python methods to leverage the rust native improvements.
- Use python native structures for the Python methods.

* Format: Remove extra blankspace

* Fix: Remove `text_signature`, use `signature` instead.

* Fix: Rectify the behavior of `qargs`
- Keep insertion order by inserting all qargs into a `PySet`.
- Perform conversion to `PyTuple` at insertion time leveraging the iterator architecture.
- Remove python side counterpart to avoid double iteration.
- Make rust-native `qargs` return an iterator.

* Fix: Corrections from Matthew's review
- Use `format!` for repr method in `InstructionProperties`
- Rename `Variable` variant of `TargetInstruction` to `Variadic`.
- Remove `internal_name` attribute from `TargetOperation`.
- Remove `VariableOperation` class.
- Use `u32` for `granularity`, `pulse_alignment`, and `acquire_alignment`.
- Use `Option` to store nullable `concurrent_measurements.
- Use `&str` instead of `String` for most function arguments.
- Use `swap_remove` to deallocate items from the provided `properties` map in `add_instruction`.
- Avoid cloning instructions, use `to_object()` instead.
- Avoid using `.to_owned()`, use `.clone()` instead.
- Remove mention of `RandomState`, use `ahash::HashSet` instead.
- Move parameter check to python in `instruction_supported`.
- Avoid exposing private attributes, use the available ones instead.
- Filter out `Varidadic` Instructions as they're not supported in rust.
- Use peekable iterator to peak at the next qargs in `generate_non_global_op_names`.
- Rename `qarg_set` to `deduplicated_qargs` in `generate_non_global_op_names`.
- Return iterator instances instead of allocated `Vec`.
- Add `python_compare` and `python_is_instance` to perform object comparison with objects that satisfy the `ToPyObject` trait.
- Other small tweaks and fixes.

* Implement a nullable dict-like structure for IndexMap (#2)

* Initial: Implement a nullable dict-like structure for IndexMap

* FIx: Erroneous item extraction from Python
- Fix error that caused `None` values to be ignored from `None` keys.
- Removed mutability from rust function argument in `add_instruction`.
   - Object is mutably referenced after option unwrapping.
- Add missing header in `nullable_index_map.rs`.
- Add Clone as a `K` and/or `V` constraint in some of the iterators.
- Remove `IntoPy` constraint from `NullableIndexMap<K, V>`.
- Add `ToPyObject` trait to `NullableIndexMap<K, V>`.

* Fix: inplace modification of Python dict.
- Perform `None` extraction from rust.
- Revert changes to `Target.py`

* Fix: Avoid double iteration by using filter_map.

* Docs: Add inline comments.

* Fix: More specific error message in `NullableIndexMap`

* Fix: Use `Mapping` as the metaclass for `Target`
- Minor corrections from Matthew's review.

* Fix: Make `Target` crate-private.
- Due to the private nature of `NullableIndexMap`, the `Target` has to be made crate private.
- Add temporary`allow(dead_code)` flag for the unused `Target` and `NullableIndexMap` methods.
- Fix docstring of `Target` struct.
- Fix docstring of `add_instruction`.
- Make several python-only operations public so they can be used with other `PyClass` instances as long as they own the gil.
- Modify `py_instruction_supported` to accept bound objects.
- Use rust-native functions for some of the instance properties.
- Rewrite `instruction` to return parameters as slice.
- `operation_names` returns an `ExactSizeIterator`.
- All rust-native methods that return an `OperationType` object, will return a `NormalOperation` instance which includes the `OperationType` and the parameters.

* Fix: Comments from Matthew's review
- Mention duplication in docstring for rust Target.
- Use f"{*:g}" to avoid printing the floating point for 0 in `Target`'s repr method.
- Add note mentioning future unit-tests in rust.

* Fix: Adapt to #12730
2024-07-25 17:41:27 +00:00
Elena Peña Tapia f5c5b37a7a
Bump main branch version post 1.2 branch (#12815) 2024-07-25 16:47:38 +00:00