Commit Graph

1635 Commits

Author SHA1 Message Date
Matthew Treinish dab572ae56
Remove namespace packaging hooks (#11223)
This commit removes the pkgutil namespace hooks that are used for
extending the `qiskit.*` and `qiskit.providers.*` namespaces from
external packages. These were previously used to enable the elements
packaging model where different parts of qiskit lived in separate python
packages under a shared namespace. This is no longer being used and
leaving the namespace extendable by external packages carries a risk of
issues or other accidental cross-interactions when an external package
gets loaded as part of Qiskit.
2023-11-09 16:01:01 +00:00
Caleb Johnson 25c46dc0e8
Allow barriers in overlap circuit inputs (#11179)
* Allow barriers in overlap circuit inputs

* Minor fixes plus test with barriers

* Check parameter number on barrier test, similar to other non-failing tests.

* test order

* Add release note
2023-11-08 11:46:58 +00:00
Raghav 838e9669a2
Removed 2pi wrapping for global phase parameter (#10631)
* removed _mod_2pi

* added release note

* Improved linting ,formatting & the fix.

* Partially fixed pylint errors

* removed redundant _mod_2pi from dynamical_decoupling

* Update releasenotes

Added PadDynamicalDecoupling class & kept higher level.

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

* Added a test.

* Replaced `try` block with `assertEqual()` statement.

* Fixup release note

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-11-06 15:01:20 +00:00
Jake Lishman 81e5ddd3ec
Expire deprecation on `qargs=None` in DAG appends (#11190)
This removes the warnings converting explicit `None`s into empty tuples,
following its deprecation in 0.45.
2023-11-06 13:00:07 +00:00
SoranaAurelia 179d9abfb5
Fix circuit drawer returning qubit[register] names for input (#11096)
* added registers to layout in sabre_layout pass

* Add reno and test

* Fix layout method in test

* Set transpiler seed

* modified reference circuit for test

---------

Co-authored-by: Elena Peña Tapia <epenatap@gmail.com>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2023-11-06 09:50:20 +00:00
Sebastian Brandhofer 8d775179d7
Improved Documentation and Error-Signaling of VF2PostLayout (#11090)
* Improves Returned Information of VF2PostLayout

* small change to class doc

* Set 'no better solution' as default

* added release note

* update reno
2023-11-03 13:27:42 +00:00
mergify[bot] b32942e073
Restore accidently deleted scheduling passes (#11184) (#11189)
In #10754 3 legacy scheduling passes were accidently deleted. These
passes were incorrectly identified as deprecated, however they were
never marked as deprecating just pending future deprecation. They were
intended to be be promoted from a pending deprecation to a full
deprecation in #8023 but we never took that step because there were
objections at the time as they still served a purpose. #10754 likely
missed this as the only indication in the deprecation decorator was a
kwarg that said `pending=True`, and this was the only indication that
these passes weren't actually deprecated yet. This commit restores these
passes on the 0.45.0 branch in the interest of unblocking the 0.45.0
release ASAP. We can handle forward porting this PR to main as needed
after the 0.45.0 release is tagged.

(cherry picked from commit aa272e9ef7)

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-11-03 11:08:02 +00:00
Jake Lishman a2c5412f87
Fix build ordering of `BlueprintCircuit._append` (#11181)
`QuantumCircuit._append` is the actual append primitive and is allowed
in inner-loop appends (and for `QuantumCircuit` to assume that it's
callable from other methods), so it's important that the "ensure built"
check happens there, not in `append`.
2023-11-02 19:29:08 +00:00
Edwin Navarro e7b1f5e69a
Update and expand DAGDependency drawer (#11103)
* Update and expand dag dependency drawer

* Increase tolerance

* Add conditions and truncate long lists

* Lint

* Cyclic import

* Lint

* Reno
2023-11-02 09:14:20 +00:00
Christopher J. Wood 34773f348f
Deprecate `PauliList` estimator observables (#11055)
* Deprecate PauliList estimator observables

Deprecates using a `PauliList` as an observable that is implicitly converted to a `SparsePauliOp` with coefficients 1 when calling `Estimator.run`. Users should instead explicitly convert the argument using `SparsePauliOp(pauli_list)` first.

* Revert algorithms_test_case.py

* Update test/python/algorithms/algorithms_test_case.py

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

* Update test/python/primitives/test_estimator.py

---------

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: ikkoham <ikkoham@users.noreply.github.com>
2023-11-02 05:08:20 +00:00
Christopher J. Wood 60de2972f0
Deprecate legacy primitive attributes in base classes (#11051)
* Deprecate legacy primitive attributes

These attributes should have already  been deprecated when the Estimator and Sampler run signatures were changed to take circuits instead of indices.

* Deprecate attributes set during init

* Fix attribute access

* fix attribute access

* simplify

* Simplify __getattr__ conditional

---------

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
2023-11-01 01:50:12 +00:00
Chris Harris b47c28bea7
Collect classical registers using a set (#10496) (#10505)
* Collect classical registers using a set (#10496)

This adds a test case that adds multiple conditions on the same
register. The test case is fixed by using a set to collect the
classical registers in collapse_to_operation.

* Add release note

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-10-31 15:41:28 +00:00
TsafrirA 7c89b68668
Deprecate the discrete pulse library (#11110)
* Promote to deprecation and correct tests

* remove `guassian` from tutorial

* Release notes

* change to 0.46.0

* Test fix

* Lynt
2023-10-31 00:02:46 +00:00
Elena Peña Tapia f0d39375ec
Fix lack of alternative for `Optimizer` in `AQC` (#11099)
* Add alternative and deprecation warning

* Add deprecation test

* Apply Julien's suggestion

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

* Apply suggestions from Julien's code review

* Move optimizer setting to init

* Fix ddt import

* Fix lint

* Add reno

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2023-10-30 12:56:47 +00:00
Luciano Bello e181eabc04
some typos in 0.45 release notes (#11100) 2023-10-27 12:25:56 +00:00
Matthew Treinish 0de8730ccb
Emit a descriptive error when the QPY version is too new (#11074)
This commit updates the qpy load() function to ensure we are raising a
descriptive error message when a user attempts to load a qpy version
that's not supported by this version of qiskit. Previously it would
fail but with a hard to understand internal error message which was just
confusing and not helpful. For example, when trying to load a QPY
version 10 payload with qiskit 0.25.2 (which only supported up to
version 9) it would raise an error message like:

```
Invalid payload format data kind 'b'p''."
```

which doesn't tell you anything meaningful unless you are intimately
familiar with the QPY file format and how the load() function works.
With this commit it now checks if the version number is supported
immediately and if it's too new it will raise an error message that says
exactly that. So in the above scenario instead of that error message it
will say:

```
The QPY format version being read, 10, isn't supported by this Qiskit
version. Please upgrade your version of Qiskit to load this QPY payload.
```
2023-10-27 12:12:32 +00:00
Matthew Treinish 0764a33b92
Always run vf2 scoring serially (#11112)
* Always run vf2 scoring serially

The VF2Layout and VF2PostLayout passes' Rust scoring function has the
option to use a parallel iterator for computing the score of a layout
given a sufficiently large circuit (both in number of 2q interactions or
qubits). Previously the scoring would be multithreaded if there were >
50 qubits or > 50 2q interactions in the circuit. However, as recent
testing has shown in most cases the performance of doing this operation
in parallel is much worse than serial execution. To address this issue,
this commit just always uses the serial version. The parallel option is
left in place for now just in case someone was manually calling the
scoring function with the parallel option set to ``True``.

* Add release note
2023-10-26 20:39:30 +00:00
AlexanderGroeger 4b5546fd8f
Plot State City Visualization Fixes (#10590)
* fix zordering and labels outside of plot

* lint and reno

* Changed reference image for state city

* correct visual of negative real value bars

* added release notes for negative real bars fix

* remove debug print statement in plot_state_city

* fix with tox eblack

* append rho to title

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

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2023-10-26 07:42:32 +00:00
Matthew Treinish 5df2439c35
Fix Barrier broadcast arguments (#11113)
This commit fixes an issue with the Barrier class's
broadcast_arguments() method. Previously the Barrier class was
overriding broadcast_arguments(), however this custom implementation
resulted in an identical output to the Instruction's implementation
(its parent class) but stripped out all the error checking to determine
if the arguments aligned with the size of the instruction. This could
result in creating a corrupt circuit that had a mismatch between the
barrier width and the number of qargs. For example:

```
circuit = QuantumCircuit(1)
circuit.append(Barrier(42), [0])
```

would not error despite trying to add a 42 qubit barrier on qubit 0.
This would result in weird errors such as invalid qpy generation that
are confusing to debug. This commit fixes this by deleting the
broadcast_arguments() implementation for Barrier so it will just
depend on the inherited implementation from Instruction which will
return an identical result but check the instruction is valid.
2023-10-25 19:58:35 +00:00
TsafrirA b2e9ebbf79
Qiskit Pulse - Introduce logical elements and frames (#10694)
* Introduce logical elements and frames.

* test fix

* Update qiskit/pulse/logical_elements_frames.py

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

* Update qiskit/pulse/logical_elements_frames.py

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

* Update qiskit/pulse/logical_elements_frames.py

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

* Update qiskit/pulse/logical_elements_frames.py

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

* Split files

* Remove name from MixedFrame

* fixes

* Update qiskit/pulse/model/__init__.py

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

* Update qiskit/pulse/model/frames.py

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

* Update qiskit/pulse/model/logical_elements.py

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

* Update qiskit/pulse/model/logical_elements.py

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

* Update qiskit/pulse/model/logical_elements.py

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

* Update qiskit/pulse/model/mixed_frames.py

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

* Update qiskit/pulse/model/mixed_frames.py

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

* Update qiskit/pulse/model/mixed_frames.py

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

* Update qiskit/pulse/model/frames.py

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

* Update qiskit/pulse/model/frames.py

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

* Update qiskit/pulse/model/logical_elements.py

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

* Update qiskit/pulse/model/logical_elements.py

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

* Update qiskit/pulse/model/logical_elements.py

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

* Update qiskit/pulse/model/logical_elements.py

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

* Update qiskit/pulse/model/__init__.py

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

* Update qiskit/pulse/model/__init__.py

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

* fixes

* doc mod name

* doc fix

* doc fix

* doc fix

* Qubit ref fix

* Qubit ref fix

* Qubit ref fix

* Qubit ref fix legacy release notes

* Update qiskit/circuit/quantumcircuit.py

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

* Update qiskit/pulse/model/__init__.py

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

* Update qiskit/pulse/model/__init__.py

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

* Update qiskit/pulse/model/mixed_frames.py

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

* Update qiskit/pulse/model/mixed_frames.py

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

* Update qiskit/pulse/model/mixed_frames.py

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

* minor fixes

* Qubit ref

* last doc fixes

* last doc fixes

* lynt

---------

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
Co-authored-by: Will Shanks <wshaos@posteo.net>
2023-10-24 15:41:08 +00:00
TsafrirA 5de1a06b03
Add disable_validation option to SymbolicPulse (#11029)
* Add disable_check option

* Remove per instance option, add release notes

* Release notes correction
2023-10-23 04:43:42 +00:00
Jun Doi d781dcc09b
Fix calling backend.name() for backendV2 (#11065)
* add check for backend version to get backend name

* move backend_interface_version

* check backend is None before get version

* Update qiskit/utils/backend_utils.py

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

* Update releasenotes/notes/fix_backend_name-e84661707058b529.yaml

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-10-21 02:08:20 +00:00
Simon Roy 828f6544ff
List support for coupling map in pass manager (#11063)
* List support for coupling map in pass manager

* remove redundant checks for coupling list in preset pass manager

* remove duplicate release note

* add seed to the coupling list test case

* Fix up release note

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-10-20 15:48:34 +00:00
Matthew Treinish 7585bd5d40
Move one last release note for 0.45.0 (#11060)
In the lead up to the 0.45.0rc1 release we used the merge queue to
pipeline the last 2 PRs that merged for the tag. However, this resulted
in a single release note file merging before we could move it into the
0.45/ subdirectory. This commit fixes this so that the final PR for
0.45.0rc1 is correctly grouped in the 0.45 release notes subdirectory.
2023-10-20 08:15:37 +00:00
Matthew Treinish fd5399bc85
Set version number to 0.45.0rc1 for first release candidate (#11028)
For the 0.45.0 release we're going to push release candidates prior to
the release to enable testing before we cut the final release. In
preparation for tagging the first release candidate this commit updates
the version string to indicate it's a release candidate. This commit
should be the final commit on main for 0.45.0rc1 and what gets tagged as
0.45.0rc1 post-merge.
2023-10-19 20:10:38 +00:00
Henry Zou 6148f903d1
Fix input normalisation of `transpile(initial_layout=...)` (#11031)
* Fixed issue10554 by modifying _parse_initial_layout in transpile to normalize input of range to a list

* Added test and bugfix note

* Handle consumable iterables

* Fix release-note cross references

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-10-19 17:11:06 +00:00
Jake Lishman cefd6a3aec
Add base-gate callback to `CUGate.params` return (#11032)
* Add base-gate callback to `CUGate.params` return

This causes item-setting in `CUGate.params` to forward those sets on to
the `UGate` in its `base_gate` unless they are setting the `gamma`
parameter, which is not shared.

`CUGate` breaks several assumptions and components of the
`ControlledGate` interface, including by having more parameters than its
`base_gate`; `ControlledGate` assumes that its subclasses will not have
a separate `_params` field, but instead will always just view onto their
`base_gate._params`.  This commit changes the behaviour of the `params`
getter to create a temporary list that backreferences to the base gate,
satisfying the requirement.

Co-authored-by: Richard Rodenbusch <rrodenbusch@gmail.com>

* Handle sliced assignments

---------

Co-authored-by: Richard Rodenbusch <rrodenbusch@gmail.com>
2023-10-19 16:42:37 +00:00
Alexander Ivrii 8d69dd0306
Merging `UnrollCustomDefinitions` into `HighLevelSynthesis` as a single pass (#10965)
* Defining and synthesizing AnnotatedOperation

* reworking annotated operation tests

* cleaning up annotated operation

* running black

* lint

* adding recurse argument and fixing the way definition is handled

* treating the case when there is no definition

* lint

* black

* removing duplicated line resulting from merge

* improving comments

* fix to merge conflicts

* black; additional fixes for prelim support of coupling map with annotated operations

* calling substitude_node with propagate_conditions=False

* black

* removing unused imports

* improving documentation of AnnotatedOperation

* minor

* release notes

* release notes typos

* restoring recursion; starting to combine UnrollCustomDefinitions

* merging in unroll_custom_definitions

* adding compatibility tests with UnrollCustomDefinitions and Unroller

* using default session equivalence library by default

* removing propagate_condition=False

* adjusting HLS options in common.py

* Removing UCD from preset pass managers as it has been replaced by HLS

* release notes

* changing default equivalence library back to empty

* typo

* fix annotations

* removing deprecated instruction from test

* removing unnecessary conversions from dag to circuit and back, and setting copy_operations to False

* fix for control-annotations for high-level-objects

* tests for inverse/control modifiers applied to high level objects

* fixes and tests for power modifiers applied to high level objects

* fixing merge problems

* lint and improving redundant conversions

* removing top_level_only

* typo
2023-10-19 15:12:10 +00:00
Santhosh G S eef868d381
Removed code deprecated in 0.22 [transpiler and providers] (#10872)
* Removed code deprecated in 0.22 [transpiler and providers] (#10813)

	* Removed the argument 'qubit_channel_mapping' in the class 'qiskit.transpiler.passes.calibration.rzx_builder.RZXCalibrationBuilder'

	* Replaced the argument 'qobj[Qobj]' in 'qiskit.providers.aer.QasmSimulator.run()' with 'qcirc[QuantumCircuit]'

	* Altered the test files accordingly

	* Added a release note

* Update release note and change input argument variable name

* Edited the docstring for the arg run_input

* Update qiskit/providers/basicaer/qasm_simulator.py

Formatted the docstring of .run() fnction as per the review suggestion

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

* Update releasenotes/notes/remove-deprecated-code-in-0.22.0-139fa09ee0cc6df9.yaml

Added extra detail on the version of ``qiskit-terra`` from which ``qubit_channel_mapping`` was depreciated

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

* Update releasenotes/notes/remove-deprecated-code-in-0.22.0-139fa09ee0cc6df9.yaml

Better formatted the release notes

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

* Update qiskit/providers/basicaer/qasm_simulator.py

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

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-10-19 13:40:31 +00:00
Matthew Treinish 4dfcba2081
Fix build filter coupling map with mix ideal/physical targets (#11009)
* Fix build filter coupling map with mix ideal/physical targets

This commit fixes a small issue in the Target.build_coupling_map method
with filter_idle_qubits=True. Previously the internal method used to
filter the idle qubits from the coupling map's creation was not
accounting for the case that an instruction in the target could be
ideal. This was never caught because normally if you have an ideal fixed
width instruction in the target that is modelling a simulator which
doesn't have any connectivity constraints and the function would never
be called. But in targets that have a mix of both ideal globally
defined and physical gates the filter code couldn't handle the None used
to represent an ideal globally available gate. This commit fixes that
handling to just ignore the global gate like the normal coupling map
construction does.

* Fix lint
2023-10-19 13:24:47 +00:00
Paul Nation 5da524b462
Add UnitaryOverlap to the circuit library (#10734)
* add overlap function

* Add tests

* add release note

* add checks for meas+reset

* update docstring

* spelling

* apply review comments

main change: check if circuits are unitary by checking if all operations are of type ``Gate``

* apply changes from review

- do not allow U/V
- allow setting parameter prefixes

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2023-10-19 10:27:17 +00:00
MozammilQ 4603e05099
schedule() considers instruction map (#10988)
* fixed_issue_10837 by taking backend from the user and passing it to measure function of macros.py in qiskit/qiskit/pulse

* removing backend argumnet from inner function.

Since, get_measure_schedule is an innner function , so backend from lower_gates will be available to the inner function, so backend argument in the inner function is redundant :)

Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>

* Fixed typo repetation of CircuitPulseDef, and removal of backend argument from the function call of get_measure_schedule

* Adding relevant docstrings in the changed methods

* fixed lint

* Added tests to use BackendV2.

* Apply suggestion in docstring.

Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>

* Apply suggestion in docstring.

Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>

* Apply suggestion in docstring.

Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>

* Apply suggestion in docstring.

Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>

* added a release note

* applied suggestions

* checked lint

* added suggestions in the release note

* Update releasenotes/notes/Adding-BackendV2-support-to-schedule-of-qiskit.compiler.scheduler-a0366d3397c73af0.yaml

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

---------

Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2023-10-19 03:16:25 +00:00
Naoki Kanazawa 7acf882c1c
Pass manager refactoring: cleanup internals (#10127)
* Refactor internals of pass manager and flow controllers.

This PR introduces two changes for
* remove tight coupling of flow controller to pass runner instance,
* remove pass normalization.

PropertySet becomes context var so that flow controllers can be instantiated
without coupling to a pass runner instance. BasePass becomes an iterable
of length 1 to skip normalization. The decoupling of property set from
pass runner allows pass manager to directly broadcast pass runner
in the multithread, rather than distributing self and craete
multiple pass runner in each thread.

* Replace class attribute PASS_RUNNER with property method.

This allows subclass to dispatch different pass runner type depending on the target code.

* Refactor passmanager module

- Add OptimizerTask as a protocol for the pass and flow controller. These are in principle the same object that inputs and outputs IR with optimization.
- A task gains execute method that takes IR and property set. This makes property set local to iteration of the passes.
- Drop dependency on pass runner. Now pass manager has a single linear flow controller.
- Pass manager gain responsibility of compiler frontend and backend as pass runner dependency is removed. This allows flow controllers to be still type agnostic.
- Drop future property set, as this is no longer necessary because optimization task has the execute method explicitly taking the property set.

* Refactor transpiler passmanager

- Remove pass runner baseclass and replace RunningPassmanager baseclass with FlowControllerLiner
- Implemented frontoend and backend functionality in transpiler Pass manager

* Rename module: base_pass -> base_optimization_tasks

* Backward compatibility fix
- Move handling of required passes to generic pass itself. This makes optimizer tasks the composite pattern-like for more readability.
- Readd MetaPass to transpiler BasePass as a metaclass which implements predefined equivalence check for all passes. This is necessary to take care of duplicated pass run, which is prohibited in circuit pass manager.
- Add FlowControllerMeta that allows users to subclass FlowController, while delegating the pass control to BaseFlowController.
- Readd count to pass manager callback
- Add PassState that manages the state of execution including PropertySet. This is a portable namespace that can be shared across passes.

* Update module documentation

* Update release note

* lint fix

* OptimizationTask -> Task

In multi-IR realm task can be something other than optimization. For example IR conversion. Name should not limit operation on subclass.

* Typo fix FlowControllerLiner -> FlowControllerLinear

* Use RunState value. Set 0 to success case.

* Separate property set from pass state. Now Task.execute method has two arguments for property set and pass state. Lifetime of property set data is entire execution of the pass manager, while that of pass state is execution of a single pass.

* Pending deprecate fenced_property_set and remove usage.

* Pending deprecate FencedObject baseclass and remove usage.

* Add some inline comments.

* Convert RunState to raw Enum

* Change the policy for the use of multiple IRs. Just updated module documentation, no actual code change. Future developer must not introduce strict type check on IR (at least in base classes in the module).

* Updated interface of base controller. Namely .append() and .passes are moved to particular subclass and the baseclass is now agnostic to construction of task pipeline. This adds more flexibility to design of conditioned pipelines.

Note that PassState is also renamed to WorkflowStatus because this is sort of global mutable variable, rather than local status information of a particular pass.

* Remove FlowControllerMeta and turn FlowController into a subclass of BaseController.

* Remove dependency on controller_factory method and deprecate.

* Update release note

* Readd code change in #10835

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

* typehint fix

* doc fix

* move FencedPropertySet class back to transpiler.fencedobjs

* Temporary: add lint ignore

* Fix example code in class doc

* Tweaks to documentation

* Change baseclass of the MetaPass and revert f28cad9

* Update interface of execute and use generator feature.
- Add new container class PassmanagerMetadata
- Rename propertyset with compilation_status
- Provide metadata with the iter_tasks instead of property_set
- Send metadata through generator
- Turn metadata required, and let pass manager create metadata
- Return metadata from execute along with the IR

* Update deprecations

* Delay instantiation of FlowControllerLinear until execution of pass manager

* Stop wrapping a list of tasks with flow controller linear.

* Remove flow_controller_conditions from base controller append and add stacklevel to deprecation warning

* Misc updates

* disable cyclic-import

* Remove typecheck

* Rename `PassmanagerMetadata` to `PassManagerState`

This is primarily to avoid a potential conflict with the terminology
`metadata` that's associated with the `input_program`, and because the
object is the state object for a pass-manager execution.  There is still
a risk of confusion with `RunState`, but since that's a subcomponent of
`PassManagerState`, it feels fair enough.

* Correct warning stacklevel

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-10-19 02:10:15 +00:00
Edwin Navarro 19862cc249
Add display of expressions to circuit drawers (#10869)
* Fix override bug and testing

* Preliminary changes

* First attempts

* Work on x_index

* Early testing

* Cleanup getattr

* Complete adding exprs

* Add exprs to mpl

* Work on spacing

* Spacing changes

* Finish initial mpl expressions

* Exprs fully implemented mpl, pre-test

* Add exprs to text drawer

* Minor text fixes and update tests for cregbundle False

* Add tests

* Lint

* Fix test

* Adjust switch test

* Lint again

* Add expr_len kwarg and minor fixes

* Update for 10842 changes

* Lint

* Update refs for minor switch spacing

* Minor cleanup

* Only call QASM3Builder once

* Remove spurious print

* Minor documentation tweaks

* For mpl, adjust switch/expr spacing, fix 1 qarg flow ops, fix top level flow op layers

* Add tests for 1 qarg, nested expr, and for range

* Lint

* Fold on text test

* Remove wire_map from get_layered

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-10-19 01:04:47 +00:00
Jake Lishman b18faa3f89
Deprecate passing `None` to `DAGCircuit` appenders (#10752)
This has been against the documented typing of the functions for some
time, but some scheduling methods have mistakenly been passing `None`.
There is no need to support `None` here; the empty tuple `()` is equally
immutable and a CPython singleton, so there are neither mutability nor
memory benefits to supporting both, and removing `None` as an input is a
simple way to remove a(n admittedly cheap) branch from the appender
methods.

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2023-10-18 15:23:14 +00:00
Raghav d86e708f11
Removed code deprecated in qiskit-terra 0.21, released on June 2022 (#10754)
* Removed code and tests deprecated in 0.21

* Undone removal of optimizers/spsa.

* undo changes in spsa

* Added release note.

* Removed deprecated classes from docstrings.

* Improved release note.

* Added removed files to resolve conflict.

* Removed the conflicting files

* Added conflicting file but with no code

* Align measure class file

* Removed alap dynamical coupling class

* Resolving colflict with dynamical coupling

* Deleted dynamical coupling

* Fixed release note.

* Apply suggestions from code review

* Update qiskit/execute_function.py

* recover benchmark test

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Luciano Bello <luciano@debian.org>
2023-10-18 12:27:04 +00:00
Julien Gacon 998b5595df
Preparations to update the default MPL drawer style to ``"iqx"`` (#10950)
* V0 of changing to IQP color

* Rename alternative color tests

- iqx -> iqp
- add test for clifford

* update Clifford reference img

* add reno

* fix reference image

* Pending deprecate IQX

* fix IQX style deprecation

* actually do fix the deprecation

* docs

* in quantumcircuit

* updates iqp name in json

---------

Co-authored-by: Luciano Bello <luciano@debian.org>
2023-10-18 11:45:49 +00:00
Alexander Ivrii a0bfb87e82
Fix commutation analysis to group gates into blocks of pairwise commuting gates (#10618)
* fix to commutative analysis to avoid unsound optimizations

* release notes

* improving release notes and adding co-author

Co-authored-by: Randl <zheltonozhskiy@gmail.com>

* replacing .i by .id in one of the added tests

* dummy commit

---------

Co-authored-by: Randl <zheltonozhskiy@gmail.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-10-17 16:32:45 +00:00
Paul Nation 881fa8eeef
Deprecate Unroller pass (#10607)
* Deprecate Unroller pass

* small fix

* black

* add release note

* fix test

* fix test again

* fix test again

* fix visualization tests

* update visual tests

* try to fix circuits

* Adjust qpy backwards compat tests to handle change in control definition

In this PR by switching the internal use of the Unroller to the
BasisTranslator for the add_control.py module results in a different
definition for the generated controlled gate than was done in previous
releases this causes the qpy backwards compat tests to fail. The qpy
backwards compatibility tests generate qpy files with every historical
release of qiskit (that had qpy support) and valdiates that if we load
those qpy files with the current state of the main branch (plus a PR
under test) that the loaded  circuits are identical to running the same
code to generate the circuit. However, because of this divergence due to
an internal change in add_control() the circuits are no longer 100%
identical, but are still equivalent. To address this, a new option is
added to the test suite to give an option when this situation occurs to
test for unitary equivalence instead of a instruction for instruction
identical circuit. This is then used for the control circuits.

* Expand release notes

* Ensure we are explicitly warning on transpile()

This commit adds an explicit user facing warning for places where the
transpiler is typically invoked by users. The normal entry point for
users that are using the unroller is to call
`transpile(..., translation_method="unroller")` and they don't work
directly with the `Unroller` pass. This means the deprecation warning
would be hidden from most users because the warning would not point to
user code and the default filters will suppress it. This commit adds an
explicit warning to transpile() and generate_preset_pass_manager() when
the unroller is requested as the translation method to ensure users see
the warning and know how to adjust.

* Apply suggestions from code review

Co-authored-by: Elena Peña Tapia <57907331+ElePT@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>
2023-10-17 15:19:56 +00:00
adigaboy 62467839e8
removed deprecated PauliTable, StabilizerTable and tests (#10815)
* removed deprecated PauliTable, StabilizerTable and tests

* remove deprecated PauliTable

* add release note

* Revert removal of pauli_basis

* fix a test

* Update releasenotes/notes/remove-deprecated-in-quantum-info-0f9bd2b0c093307d.yaml

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

---------

Co-authored-by: ikkoham <ikkoham@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-10-17 00:25:29 +00:00
Luciano Bello 458ad13ded
NoiseAdaptiveLayout to consider inconsistencies in backend (#10859)
* filter backend_prop when does not match the size of the device

* NoiseAdaptiveLayout to consider inconsistencies in backend

* extend docstring with the warning that the parameter might be ignored

* remove the ginfo.gate and just find two-qubit gates

* edge_set

* deepcopy

* extend test

* Attempt to fix docs build error

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-10-16 23:41:24 +00:00
Matthew Treinish 111fd64d2c
Singleton parameterless controlled gates (#10898)
* Singleton parameterless controlled gates

This commit adds a new class SingletonControlledGate which is very
similar to the SingletonGate class, but instead can be used in place of
the ControlledGate class as a parent class. This enables a controlled
gate class to work as a singleton if there is no custom control state
specified. This new class has a large amount of duplication with the
SingletonGate class, but because of how the inheritance tree is built
up here there is no avoiding this as we need to specialize for adding
singleton support and SingletonGate is at the same level as
ControlledGate.

With the introduction of this new class all the standard library
ControlledGate instances are updated so they inherit from
SingletonControlledGate instead of ControlledGate. This should
significantly reduce the memory footprint of repeated instances of these
gates in circuits.

* Fix failing test cases

* Apply suggestions from code review

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

* Fixes from rebase

* Fix cyclic imports caused by eager definition population

* Fix tests

* Remove unused changes to ControlledGate

* Expand deepcopy test assertions

* Update release notes

---------

Co-authored-by: Kevin Hartman <kevin@hart.mn>
2023-10-16 19:50:01 +00:00
Jake Lishman f87bb0132d
Use only discrete-basis translations in `GateDirection` (#10786)
* Use only discrete-basis translations in `GateDirection`

This makes it a little more likely that it'll be possible to use the
transpiler when targetting a discrete basis, such as a Clifford
simulator.  We still in general do not offer full support for
discrete-basis translation, and certainly not for optimal discrete-basis
transpilation, but this is a relatively easy change that makes us
marginally more reliable with them.

* Fix global phase in tests
2023-10-16 17:59:17 +00:00
Alexander Ivrii df9eae42c4
Starting layout analysis pass for sabre (#10829)
* adding SabreStartingLayoutUsingVF2 analysis pass

* fixing imports

* bug fix

* fixing test after changing some of the options

* renaming

* adding target; more renaming; tests

* release notes

* applying suggestions from code review

* removing debug print

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

I didn't know this existed :)

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

* adding missing :

* collecting edges into a set

* adjusting error_rate with respect to distance

* letting coupling_map be either coupling map or target, for consistency with other passes

* apply suggestions from code review

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

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-10-16 16:14:32 +00:00
Jake Lishman 3b97b3745e
Fix deprecation warning of unscheduled circuits in timeline drawer (#10851)
The warning was previously emitted with a `stacklevel` that blamed the
caller of `warnings.warn`, which would not be shown to users with the
default warning filters.  This moves the stack level up to blame the
caller of `timeline_drawer`.
2023-10-16 13:39:14 +00:00
jaeunkim fc74ab96b1
Add NormalizeRXAngle and RXCalibrationBuilder passes (#10634)
* Added NormalizeRXAngle and RXCalibrationBuilder passes to build single-pulse RX gate calibrations

* Fixed a typo in documentation

* Removed all cross-references in the documentation

* Added URL links back

* Added cross references back to the release note

* Shorten the cross references in the release note

* Fixed normalize_rx_angle.py based on the comments

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

Edit the doc so that it looks nicer in html

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

* Reformat the doc of NormalizeRXAngle

* Try to pass the doc test

* Addressed feedback and comments from the code review

* Yet another attempt to fix docs error

* Fix docs

* Add 'atol=resolution/2' to np.isclose() tests for SX and X

* fix typo

* Elaborate on quantize_angles()

* Add a demo with a QuantumVolume circuit

* Check pulse.pulse_type==Drag instead of isinstance(pulse, Drag)

---------

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2023-10-16 05:26:41 +00:00
Elena Peña Tapia 9843fbfe7b
Fix qpy for controlled `UnitaryGate` (#10809)
* Add exception for controlled gate

* Add reno

* Add fix

* Adjust test

* Update test/python/circuit/test_circuit_load_from_qpy.py

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

* Fix bug with ucr*-dg gates

* Fix typos in comments

* Fix typo again

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-10-13 20:04:45 +00:00
Jake Lishman bcf5ce4951
Rewrite singleton handling including `SingletonInstruction` (#11014)
* Rewrite singleton handling including `SingletonInstruction`

This is a large rewrite of the singleton gate handling, building off the
work done across the library to make the initial implementation work.

There are two main purposes to this commit:

* Make `SingletonInstruction` available in addition to `SingletonGate`,
  and have these be easy to maintain in conjunction, not need to
  duplicate overrides between them, and not require inheritors to do any
  nasty multiple inheritance or the like.

* Fix regressions in the construction time of `SingletonGate` instances.

In the end, this turned into a fairly complete rewrite that completely
switches out the method of defining the classes; it transpires that the
previous way of having the "immutable overrides" on _all_ instances of
the classes was the main source of slowdown, with `__setattr__` being a
large problem.  The previous method was far easier from an
implementation perspective, but the runtime costs ended up being too
high.

This new form takes a vastly different strategy, explained in detail in
`qiskit/circuit/singleton.py`.  The gist is that we instead make the
singleton instance a _subclass_ of the class object we're creating, and
only it contains the overrides to make itself immutable.  We get around
the instantiation problem (`__init__` isn't special and doesn't
skip the forbidden `__setattr__`) by constructing an instance of the
_base_ class, and then dynamically switching in the overrides
afterwards.  Since the overrides and the dynamic singleton type of the
instance are designed to be co-operative (including in `__slots__`
layout), this can be done safely.

* Make singleton documentation public

* Add tests of new singleton behaviour

* Fix typos

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-10-13 19:04:48 +00:00
Elena Peña Tapia 65e8c1a774
Deprecation of algorithm utils (`algorithm_globals` and `validation`) (#10905)
* Add deprecation warnings

* Warnings, alg_globals, QDrift

* Move rng to init

* Add warnings alg. globals, fix tests

* Add reno

* Fix opflow tests

* Fix final test

* Update reno, deprecation messages

* Fix typo
2023-10-12 14:47:38 +00:00
Alexander Ivrii 215637537b
Annotated operations (#9846)
* Defining and synthesizing AnnotatedOperation

* reworking annotated operation tests

* cleaning up annotated operation

* running black

* lint

* adding recurse argument and fixing the way definition is handled

* treating the case when there is no definition

* lint

* black

* removing duplicated line resulting from merge

* improving comments

* fix to merge conflicts

* black; additional fixes for prelim support of coupling map with annotated operations

* calling substitude_node with propagate_conditions=False

* black

* removing unused imports

* improving documentation of AnnotatedOperation

* minor

* release notes

* release notes typos

* removing propagate_conditions

* applying suggestions from review

* tests for full transpiler flow, with and without backend

* not replace dag.op when op did not change
2023-10-12 14:13:15 +00:00
Jake Lishman dbc3e328bc
Add global-phase support to control-flow builders (#10800)
This formalises the concept of global phase within control-flow scopes,
and teaches the control-flow builders to treat modifications to the
global phase as being conditional on the control-flow block being
entered.
2023-10-11 12:43:10 +00:00
Ikko Hamamura be2cebcfb1
BackendEstimator support BackendV2 without coupling_map (#10956)
* BackendEstimator support BackendV2 without coupling_map

* revert unnecessary type

* add unittest

* lint

* refactoring

* add release note

---------

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
2023-10-11 06:27:34 +00:00
Matthew Treinish 947e175edc
Add `apply_layout` method to `SparsePauliOp` (#10947)
* Add apply_layout method to SparsePauliOp

This commit adds a new method, `apply_layout`, to the `SparsePauliOp`
class. It takes in either a `TranspileLayout` object or a list of
indices that represent a layout transformation caused by the transpiler
and then returns a new SparsePauliOp object that applies a matching
transformation.

* Fix docs typo

* Update releasenotes/notes/sparse-pauli-op-apply-layout-43149125d29ad015.yaml

* Apply suggestions from code review

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

* Fix release note typo

---------

Co-authored-by: Kevin Hartman <kevin@hart.mn>
2023-10-10 18:46:40 +00:00
Jake Lishman 8651d34ad9
Fix hash of `Parameter` and `ParameterExpression` (#10875)
* Fix hash of `Parameter` and `ParameterExpression`

This fixes the construction paths for `Parameter` and its hash such that
it will now correctly hash equal to any `ParameterExpression`s that it
compares equal to.  This is a requirement of the Python data model for
hashmaps and hashsets, which previously we were breaking.  In order to
achieve this, we slightly modify the hash key such that the `Parameter`
instances are no longer a part of the hash of `ParameterExpression`,
which means we can use the same hashing strategy for both.

This rearrangement has the benefit of removing the requirement for the
`__new__` overrides on `Parameter` and `ParameterVectorElement`.

* Add type hint

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

* Tweak documentation wording

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-10-10 16:29:35 +00:00
Kyle Lund 023569b7c8
Remove code deprecated in 0.15 (#10779)
* Removed deprecated references to Rho in plot_state_hinton, plot_bloch_multivector, plot_state_city, plot_state_paulivec, and plot_state_qsphere. Removed scheduler.utils as functions were moved to pulse/macros and pulse/utils

* Added release note

* Lint check suggestions implemented, unused import of deprecate_arg removed

* Release note section changed to upgrade

* Update releasenotes/notes/remove_depreciated_0.15_code-ee5c7d343e310888.yaml

* reno

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Luciano Bello <luciano@debian.org>
2023-10-10 11:36:43 +00:00
Jake Lishman 2b2b079c22
Fix deprecated behaviour in timeline drawer (#10846)
Internally, it removes all use of the deprecated `Bit` properties
`Bit.index` and `Bit.register`.  This is achieved by making it possible
for generator functions to accept the complete `QuantumCircuit` program
as a keyword argument, if they advertise that they can handle this by
setting a special `accepts_program` attribute on themselves to `True`.
This somewhat convoluted setup is because the generator functions are
supposed to be arbitrary and user-definable in custom stylesheets, so
we cannot unilaterally change the call signature.
2023-10-10 11:36:36 +00:00
Julien Gacon 5f53e3319c
Fix IQX color schemes (#10941)
* fix diagonal gate colors

* fix iqx-dark and iswap

* add reno

* update reference images
2023-10-06 11:35:48 +00:00
Ikko Hamamura 660448c02e
Support dynamic circuit in BackendEstimator (#9700)
* Support dynamic circuit in Estimator

* fix lint

* revert the validation condition

* fix test

* add reno

* separate measurements

* lint

* add test and bug fix reno

* fix reno

* revise tests and fix typo

---------

Co-authored-by: Takashi Imamichi <imamichi@jp.ibm.com>
2023-10-06 05:22:44 +00:00
ewinston dda063e4eb
Fix bug in qs_decomposition (#10850)
* fix bug in qs_decomposition

* reno

---------

Co-authored-by: Luciano Bello <luciano@debian.org>
2023-10-03 13:15:59 +00:00
Matthew Treinish 19854d193a
Improve the ergonomics of the TranspileLayout class (#10835)
* Improve the ergonomics of the TranspileLayout class

This commit updates the TranspileLayout class to make it easier to work
with. The TranspileLayout class was orginally just an a container class
that took the information returned from the transpiler needed to reverse
the transpiler layout permutation (in the absence of ancillas) so that
`QuantumCircuit.from_circuit()` could compare Operator instances across
a `transpile()`. However, the internal data structures used by the
transpiler are hard to work with, and don't map well to the normal
reasoning around how the transpiler transforms the circuit. To improve
the usability of the class this commit adds 4 new methods to the class:

 - initial_layout_list() and final_layout_list() which compute a list
   form of the initial_layout and final_layout respectively
 - full_layout() which generates a list that maps the input circuits
   qubit positions in the input circuit to the final position at
   the end of the circuit (which is what most people think of when they
   hear "final layout")
 - permute_sparse_pauli_op() which takes in a SparsePauliOp object and
   permutes it based on the full layout. This is especially useful when
   combined with the Estimator primitive

To implement these functions a few extra pieces of information are
needed to fully implement them. The first is we need to know the number
of original circuit qubits. This is used to account for any ancillas
that are added in the circuit, once we have the input circuit count we
can use the original_qubit_indices attribute to discern which qubits in
the initial layout are from the original circuit and which are ancillas.
The second piece of information needed is the list of qubits in the
output circuit. as this is needed to look up the position of the virtual
qubit in the final_layout. These are both added as optional private
attributes to the TranspileLayout class and there are some small changes
to the pass manager and QPY to accomodate them.

Similarly the change in the TranspileLayout class requires a new QPY
version to include the missing details that were not being serialized
in QPY and weren't representable in the previous payload format.

Fixes #10826
Fixes #10818

* Handle None for the private TranspileLayout fields in QPY

* Add test for full_layout with ancillas

* Rework interface to be more consistent

This commit reworks the names of the new methods added in this API to be
more self consistent. It uses the format '*_index_layout' to replace the
`*_layout_list` name. Similarly new methods `*_virtual_layout` are added
for methods that return layout objects.

* Apply suggestions from code review

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

* Remove permute_sparse_pauli_op()

This commit remove the TranspileLayout.permute_sparse_pauli_op() method.
This was a bit out of place on the TranspileLayout class, and it will
instead be replaced in a follow-up PR by a apply_layout() method on the
SparePauliOp class that takes in a TranspileLayout object.

* Update docs

* Fix docs build post-rebase

* Fix docs issues

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-10-03 00:43:22 +00:00
Matthew Treinish 81e28dc2a6
Add `check_input` option to `UnitaryGate` (#10660)
* Add skip_check option to UnitaryGate

This commit adds a new option to the unitary gate class's constructor,
skip_check, which is used to skip the checking on the input unitary.
When creating a unitary gates when you know the input is already unitary
checking that the input matrix is unitary is wasted CPU time. This new
option enables a user to assert the input is unitary and skip this
checking (at their own risk). The primary use case for this is the
consolidate blocks pass which is creating a large number of UnitaryGate
objects and matrix is always going to be unitary. This new flag is used
in ConsolidateBlocks to speed up the creation of gate objects.

* Rename argument check_input

* Fix rebase issues

* Update qiskit/circuit/library/generalized_gates/unitary.py
2023-10-02 18:27:45 +00:00
Julien Gacon a4ca0caa44
Deprecate duplicate circuit gate method (#10797)
* Pending-deprecate duplicate circuit methods

* Missed some old methods

* may darkness rule (aka "run black")

* Deprecate and id not i

* use id over i

* capture Aer's usage of QuantumCircuit.i

* catch warning, don't assert

* try fix errors

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

* Attempt 2 of ?

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

* Attempt 3 of 3 (hopefully)

* redundant "+"

* Filter the deprecation warning globally

* add reno

---------

Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
2023-09-29 15:21:38 +00:00
Edwin Navarro 404df43277
Fix issues with ControlFlowOp displays (#10842)
* Fix override bug and testing

* Preliminary changes

* First attempts

* Work on x_index

* Early testing

* Cleanup getattr

* Complete adding exprs

* First fix for cregbundle control flow

* Finish basic cregbundle mods

* Finish all cregbundle except wire_map bug

* Move carg check to circuit_vis and change text tests to circuit_drawer

* Move mpl tests to use circuit_drawer and update images for cregbundle changes

* Change mpl tests to circuit_drawer

* Fix flow_wire_map and tranpile bug

* Final cleanup

* Missing outputs on mpl tests

* Fix output

* Restore tests and move carg check to text and mpl and make circuit

* Prepare final cregbundle fix

* Update ref images

* Fixing refs

* Update refs again

* Final mods

* Incorporate mtreinish changes

* Add reno

* Fix if_else_op test

* Lint

* Fix target == expr bug in text

* Review fixes and outer_circuit, wire_map fixes

* Remove png

* Minor changes

* Fix for_loop measure placement bug

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-09-29 13:41:33 +00:00
Luciano Bello d365009403
Remove deprecated `x` and `z` arguments to `Pauli` (#10717)
* remove arg

* black

* reno
2023-09-29 13:19:50 +00:00
Julien Gacon 35d09364d4
Deprecate ``qiskit.extensions`` (#10725)
* big moves, import still works

* most tests pass (some I cannot seem to run locally)

* fix tests -- how to remove DiagonalGate?

* typehints and docs

* more type hints

* Deprecate SQU

* deprecate Snapshot

* Fix missing future annotations import

* minimize deprecation effort

* Change to pending deprecation, no exact-location import supported

* fix MCG<->MGC typo and snapshot deprecation

* fix pylint, try fixing docs

* remove gates from extensions toctree

* Add reno, fully deprecate SQU and Snapshot

* Apply Sasha's review comments

- fix usage of .squ and .snapshot w/o import
- fix docstring usage of extensions
- fix tests

* capture snapshot deprecation warning

* review comments

- capture warning of SQU
- update reno to explicitly mention pending deprecation, add DiagonalGate and ExtensionError

* missed `diagonal` method

---------

Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>
2023-09-29 08:11:51 +00:00
Luciano Bello e5420d2871
reduce decimal for probabilities_dict in Sampler (#10596)
* reduce decimal for probabilities_dict in Sampler

* adjust qaoa tests

* adjust qaoa tests

* reno

* Rolling everything back and just hook __repr__

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

* remove reno

* QuasiDistribution.__repr__

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
2023-09-28 15:12:49 +00:00
Elena Peña Tapia e3155c60ec
Fix `MergeAdjacentBarriers` to scale with number of barriers (#10900)
* Modify scaling

* Remove copy, add reno

* Fix lint

* Fix reno

* Update qiskit/transpiler/passes/utils/merge_adjacent_barriers.py

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

* Fix black

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-09-28 11:32:35 +00:00
Toshinari Itoko daf3f4e2f6
Fix Clifford.from_operator to fail with non-Clifford diagonal operators (#10904)
* Fix a bug in Clifford.from_matrix and from_operator

* Minor change in a comment
2023-09-28 08:21:02 +00:00
Elena Peña Tapia b8b3d58af0
Add `use_symengine` option to `qpy.dump` (#10820)
* Add use-symengine option

* Fix lint

* Improve error message

* Apply feedback

* Update docs

* Move option to file header, add schedule block

* Add example to docs

* Fix lint

* Apply second round of feedback

* Fix lint, update tests

* Update docs

* Fix use of require_now

* Fix compatibility test

* Make tests optional

* Fix lint

* Add release note

* Update exception message

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

* Update other message

* Rename Encoding to SymExprEncoding

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-09-27 16:16:25 +00:00
Luciano Bello 682eccdc0d
Removed deprecated functions in qiskit.scheduler.utils (#10879)
* reno

* fix reno

* remove cross-reference
2023-09-25 10:43:56 +00:00
AlexanderGroeger 6a38279c29
Support passing empty lists to Pauli delete method (#10849)
* handle empty lists in delete methods, added release notes

* fixed ordering of empty list check in pauli delete method

* add proper cross-references to classes

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

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-09-22 22:29:21 +00:00
Jake Lishman 846d3295a2
Pin Numpy < 2 in requirements (#10893)
We have compiled extensions that are built against the Numpy C API.  The
Numpy transition guide for developers of downstream packages[^1]
encourages us to put in this pin until we have wheels built against the
newer version, which is not expected to be fully ABI compatible (but
extensions built against Numpy 2 _should_ work with older Numpys).

Note that this won't prevent package managers from resolving _older_
versions of Qiskit (which don't have the pin) along with Numpy 2, but
there's not a vast amount we can do about that now.

[^1]: https://github.com/numpy/numpy/issues/24300
2023-09-22 21:50:21 +00:00
Mahnoor Fatima 778acaf32d
Update plot_gate_map() family to leverage graphviz for visualization (#10208)
* Update gate_map.py

Update the gate_map.py to migrate the visualization modules from matplotlib to rustworkx.graphviz

* Removed has_rustworkx instances

* Added release notes

* Update test_gate_map.py

Updated tests for the modified gate_map.py file

* Formatted gate_map.py

* Format test_gate_map.py

* Added release notes for the fix of #9031

* Update gate_map.py

* Update test_gate_map.py

Test file updated so that all tests can be passed.

* Update test_gate_map.py

* Update gate_map.py for rerunning tests.

* Update test_clifford.py

* Update gate_map.py to reuse rx.draw_graphiz

* Update test_gate_map.py to omit qubit_visualization

* Update test_gate_map.py to fix formatting changes

* Update gate_map.py

* Update gate_map.py

* Update gate_map.py

* Update test_gate_map.py

* Update test_gate_map.py

* Update gate_map.py

* Update gate_map.py

* Update gate_map.py

* Update gate_map.py

* Update gate_map.py

* Update gate_map.py

* Update gate_map.py

* Update test_gate_map.py

* Update test_gate_map.py to add rx import

* Update test_gate_map.py

* Update test_gate_map.py

* Update test_gate_map.py to fix imports

* Update test_gate_map.py to add HAS_GRAPHVIZ to all tests

* Update test_graph_matplotlib_drawer.py to have HAS_GRAPHVIZ

* Update test_graph_matplotlib_drawer.py to add HAS_GRAPHVIZ import to test_font_color function

* Update test_graph_matplotlib_drawer.py to add GRAPHVIZ check to the class

* Update test_graph_matplotlib_drawer.py to add HAS_GRAPHVIZ to both gate_plot_map and test_gate_plot_map import to test_font_color function

* Update test_graph_matplotlib_drawer.py

* Update test_graph_matplotlib_drawer.py

* Update test_graph_matplotlib_drawer.py

* Fixed the `font_color` parameter in `gate_map.py/plot_gate_map()`

The font_color parameter can now accept hex values as well.

* Modify color_edge function to increase speed

* Update gate_map.py to fix formatting

* Update gate_map.py to shift seaborn import to `plot_error_map`

* Add HAS_SEABORN to test_plot_error_map

* Reformat gate_map.py

* Fixed node autoscaling in `gate_map.py` graphs

* Add return type to `test_from_gate_with_cyclic_definition ` in `test_clifford.py`

* Update update-gate_map-visualizations-6ea907a0502fdc1a.yaml

* Rename update-gate_map-visualizations-6ea907a0502fdc1a.yaml to update-gate-map-visualizations-6ea907a0502fdc1a.yaml

* Update update-gate-map-visualizations-6ea907a0502fdc1a.yaml

* Update update-gate-map-visualizations-6ea907a0502fdc1a.yaml

* Update pauli_op.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update operator.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update pauli_sum_op.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update random.py to use np.product

`np.product` is deprecated and is causing test fails.

* Update chi.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Replace np.product with np.prod

`np.product` is deprecated and is causing test fails.

* Update ptm.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update stinespring.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update superop.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update transformations.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update densitymatrix.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update random.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update statevector.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update local_readout_mitigator.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update unitary_synthesis.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update test_random.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update test_scalar_op.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update test_random.py to use np.prod

`np.product` is deprecated and is causing test fails.

* Update test_clifford.py to remove debugging code

* Move matplotlib imports to occur at run time

* Apply suggestions from code review

* Move matplotlib_close_if_inline to runtime import too

* Flatten parallel edges

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

* Fix 1 qubit backend handling

* Fix qubit label and font sizes

* new reference images

* Adjust font scaling

* Update reference images

* Remove unrelated reference file update

* Improve formatting

* Adjust pixel scaling factor

* Update reference images with formatting changes

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2023-09-22 20:58:36 +00:00
Luciano Bello 24e3f71731
remove qiskit.utils.deprecation.deprecate_function, deprecated in terra 0.22 (#10881) 2023-09-22 15:58:16 +00:00
Kevin J. Sung 364debc8dc
fix random statevector distribution (#10866)
* fix random statevector distribution

* add citation and release note

* mention Haar measure in doc and use link in release note

* cite better reference

* Format reference

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2023-09-22 10:10:59 +00:00
SamD-1998 b483a76974
#10360 New sign feature in parameterexpression.py (#10571)
* Add sign() method to ParameterExpression

This method allows applying the sign operation to an expression with
possibly unassigned parameters.

* Update releasenotes/notes/added-sign-feature-parameterexpression-57693dd69103dc8c.yaml

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

* Update releasenotes/notes/added-sign-feature-parameterexpression-57693dd69103dc8c.yaml

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

* Update releasenotes/notes/added-sign-feature-parameterexpression-57693dd69103dc8c.yaml

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

---------

Co-authored-by: Will Shanks <wshaos@posteo.net>
Co-authored-by: Will Shanks <willshanks@us.ibm.com>
2023-09-21 19:46:27 +00:00
Joonghoon Lee d55965993d
Remove quantum_info deprecated code in 0.22 (#10861)
* remove deprecated code in 0.22

* update docs

* Update releasenotes/notes/remove-deprecated-code-in-0.22-128475199e6f3cc2.yaml

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2023-09-20 19:34:43 +00:00
Alexander Ivrii 01bb111cfa
adding an option to CouplingMap.reduce to allow disconnected coupling maps (#10863)
* adding an option to CouplingMap.reduce to allow disconnected coupling maps

* missing 'not'
2023-09-20 07:05:49 +00:00
Matthew Treinish e62c86bbc2
Use singletons for standard library unparameterized, non-controlled gates (#10314)
* Use singletons for standard library unparameterized, non-controlled gates

This commit adds a new class SingletonGate which is a Gate subclass that
reuses a single instance by default for all instances of a particular
class. This greatly reduces the memory overhead and significant improves
the construction speed for making multiple instances of the same gate.
The tradeoff is in the flexibility of use because it precludes having
any potentially mutable state in the shared instance. This is a large
change to the data model of qiskit because it previously could be
assumed that any gate instance was unique and there weren't any
unintended side effects from modifying it in isolation (for example
doing XGate().label = 'foo' wouldn't potentially break other code).
To limit the impact around this instances of SingletonGate do not allow
mutation of an existing instance. This can (and likely will) cause
unexpected issues as usage of the class is released. Specifically what
used to be valid will now raise an exception because it is a shared
instance. This is evident from the code modifications necessary to
most of the Qiskit code base to enable working with instances of
SingletonGates. The knock on effects of this downstream are likely
significant and managing how we roll this feature out is going to be
equally if not more important than the feature itself. This is why
I'm not personally convinced we want to do all this commit includes
in a single release. I've opened this as a pull request primarily to
start the conversation on how we want to do the roll out to try and
minimize and notify downstream users of the potential breakage to
avoid issues. The primary issue I have is this doesn't really follow
the Qiskit deprecation policy as there is no user facing notification
or documentation of this pending change and code that worked in the
previously release will not work in the release with this feature.
For some aspects of this change (primarily the setters on gate
attributes) this can easily be handled by deprecating it in planned
singleton standard library gates and waiting the necessary amount of
time. But the more fundamental data model changes are hard to announce
ahead of time. We can have a release note about it coming in the future
but it will end up being very abstract and users will not necessarily
be able to act on it ahead of time without concrete examples to test
with. This was an issue for me in developing this feature as I couldn't
anticipate where API breakages would occur until I switched over all the
standard library gates, and there still might be others.

Due to the large performance gains this offers and also in the
interest of testing the API implications of using singleton gates the
unparameterized and non-controlled gates available in
qiskit.circuit.library.standard_gates are all updated to be subclasses
of singleton gates. In aggregate this is causing construction to be
roughly 6x faster and building circuits comprised solely of these gates
consume 1/4th the memory as before. But it also exposed a large number
of internal changes we needed to make to the wider circuit, QPY, qasm2,
dagcircuit, transpiler, converters, and test modules to support working
with singleton gates.

Besides this there are a couple seemingly unrelated API changes in
this PR and it is caused by inconsistencies in the Instruction/Gate
API that were preventing this from working. The first which is the
ECRGate class was missing a label kwarg in the parent. Similarly
all Gate classes and subclasses were missing duration and unit
kwargs on their constructors. These are necessary to be able to use
these fields on singletons because we need an interface to construct
an instance that has the state set so we avoid the use of the global
shared instance. In the release notes I labeled these as bugfixes,
because in all the cases the parent clases were exposing these
interfaces and it primarily is an oversight that they were missing
in these places. But personally this does seem more like something
we'd normally document as a feature rather than a bugfix.

A follow up PR will add a SingletonControlledGate class which will
be similar to SingletonGate but will offer two singleton instance
based on the value of ctrl_state (and also handle nested labels
and other nested mutable state in the base gate). We can then update
the standard library gates like CXGate, and CHGate to also be
singletons. The ctrl state attribute is primarily why these gates
were not included in this commit.

* Fix Python 3.8 compatibility

There are some differences in how the inspect stdlib module behaves
between python 3.8 and newer versions of python. This was causing
divergence in the test and qpy behavior where inspect was used to
determine different aspects of a gate (either whether label was
supported as an arg or find the number of free parameters). This commit
fixes this by adjusting the code to handle both newer versions of
inspect as well as older ones.

* Simplify qpy deserialization label handling

* Remove unused classmethod decorator

* Fix lint

* Fix timeline drawer on output of legacy DD pass

* Fix doc build

* Add methods to deal with mutability of singleton gates

This commit adds two methods to the SingletonGate class, mutable and
to_mutable. The mutable() method is a property method that returns
whether a particular instance is mutable or a shared singleton instance.
The second method to_mutable() returns a mutable copy of the gate.

* Disallow custom attribute on singleton instances

This commit adds a __setattr__ method to the singleton gate class to
ensure that custom attributes are not settable for a shared singleton
instance. It prevents addign a custom attribute if the instance is in
singleton mode and will raise a NotImplementedError to avoid silently
sharing state in the single shared instance.

* Fix rebase error

* Fix rebase issues

* Fix module docstring

* Add .mutable and .to_mutable() to Instruction

To unify the access patterns between SingletonGates and other
instructions this commit adds a common property mutable and method
to_mutable() to check if any Instruction (not just singletons) are
mutable or not and to get a mutable copy. For things that don't inherit
from SingletonGate these are hard coded to `True` and to return a copy
as by default every Instruction is mutable, only `SingletonGate` objects
are different in this regard.

* Unify handling of gates in scheduling passes

Previously we were explicitly handling the SingletonGate class in the
scheduling passes. But with the introduction of mutable and to_mutable()
on Instruction we don't need to condition on gates being singleton or
not and we can just handle them in the same manner as other
instructions. This commit implements this change.

* Remove unnecessary deepcopy in substitute_node_wtih_dag

* Fix logic for SingletonGate.copy

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

* Update Singleton Gate class docstring

* Remove unused imports

* Update release notes

* Fix release note typos

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

* Improve setattr performance

* Fix deepcopy logic

* Add check for kwargs up front

* Fix docs typos

* Add comment on to_mutable __init__ call

* Fix lint

* Handle positional initialization arguments in SingletonGate

If there are any positional arguments set when initializing a new
SingletonGate subclass those were not being handled correctly before. If
there is a positional argument being set that would indicate at least a
label is being set and indicates a mutable instance should be returned
instead of the immutable singleton. This commit adds the missing check
to the __new__ logic and also adds a test to verify the behavior is
correct.

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-09-19 19:41:30 +00:00
Joonghoon Lee 2d3632fee6
Remove deprecated code in 0.19 (#10791)
* remove-deprecated-code-in-0.19

* update docs

* Apply suggestions from code review

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

* remove unused function

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2023-09-16 20:27:02 +00:00
Will Shanks 4e49a56945
Allow dynamical decoupling pass to work on circuits with pulse gates (#10834)
The pass was accessing the circuit calibrations incorrectly, resulting in
an error when one of the gates in the dynamical decoupling sequence had
a pulse gate calibration.
2023-09-15 23:45:25 +00:00
Jake Lishman 05e24d51d8
Optimise `QuantumCircuit.assign_parameters` for single-parameter binding (#10548)
When assigning parameters in a heavily parametrised circuit, a
significant amount of time was spent constructing a new set of all the
`Parameter` instances used in a circuit.  This completely dominated the
execution time for the case of binding a single parameter out of a
many-parameters circuit in place.

This modifies the internal-only method
`QuantumCircuit._unsorted_parameters` to directly return the set object
already constructed by the `ParameterTable` tracking the operations,
which makes the function close to free to call, at the cost that
internal users of that function must take care not to mutate the output.
This is not generally a problem, since no code in Terra outside of
`QuantumCircuit` uses that method (nor should it!), and `QuantumCircuit`
never needs to mutate that set.
2023-09-15 11:07:49 +00:00
Jake Lishman 67021e4c37
Add fast path to `Parameter.assign` (#10549)
This specialises `Parameter.assign` to more efficiently handle parameter
assignment via `QuantumCircuit.assign_parameters`.  The assignment can
either be of `self`, and therefore should just return the value lifted
to a `ParameterExpression`, or it's not of `self`, in which case we need
to raise an error to match the superclass implementation.

The overhead of all the checks that go on during the regular
`ParameterExpression.assign` (delegating to `subs` or `bind`) are a
sizeable chunk of the cost of assignment in PEC-style circuits.
2023-09-15 07:50:11 +00:00
Christopher J. Wood 3a49759aaf
Fix GateDirection pass (#10825)
* Fix GateDirection

* Fix black

* Add note about qubit index assumption to class docstring

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-09-14 13:54:00 +00:00
Matthew Treinish 578e109a11
Add option to SabreLayout to specify starting layouts (#10721)
* Add option to SabreLayout to specify starting layouts

The SabreLayout pass typically starts with each layout trial with a
random starting layout. However, in some cases starting with a specific
starting layout can result in better output quality than starting with
a fully random layout. To use this feature an analysis pass can set a
new `sabre_starting_layout` field in the property set before
`SabreLayout` with a list of layout objects that will add additional
trials using each layout as a starting layout.

* Fix lint

* Combine random layout and partial layouts

* Expand property set docs

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

* Simplify branching logic for parallelism

* Use a slice for starting_layout in a trial

* Update releasenotes/notes/seed-sabre-with-layout-17d46e1a6f516b0e.yaml

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

* Make starting layout variable names plural

The starting layout is a list and can have more than one entry. To make
this clearer, this commit renames starting_layout -> starting_layouts
and sabre_starting_layout -> sabre_starting_layouts.

* Update releasenotes/notes/seed-sabre-with-layout-17d46e1a6f516b0e.yaml

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

* Update property set key in test

* Update test to only use partial layout

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-09-12 22:42:58 +00:00
Raghav 29dddabb6f
Removed code deprecated in 0.20 (#10767)
* Remove code deprecated in 0.20

* Removed deprated tests in 0.20

* Removed deprecated tests in 0.20.

* Added release note and reviewed changes

* Renamed test_copy_circuit_metadata and fixed syntax in release note.

* Accommodated the suggested changes in release note.

* Resolved conflict and linting
2023-09-12 20:40:03 +00:00
Matthew Treinish 2ab1e547e7
Remove deprecated BIPMapping pass (#10526)
* Remove deprecated BIPMapping pass

This commit removes the deprecated BIPMapping pass. It was deprecated in
qiskit-terra 0.24.0 and the minimum deprecation period has elapsed for
the Qiskit 0.45.0 release. This pass has been moved to an external
plugin that can be installed separately and integrated into the
transpiler more cleanly than a single pass and also separates the
optional dependency on the proprietary CPLEX into a separate package.

* Apply suggestions from code review

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

* Remove additional uses of BIPMapping

There were still two locations where the BIPMapping pass was being used.
First the dedicated unit tests, and then also import redirects for the
docs and easier access. This commit removes these locations so nothing
left is using the BIPMapping pass.

* Update optionals documentation

* Update install commands

---------

Co-authored-by: Kevin Hartman <kevin@hart.mn>
2023-09-12 15:44:25 +00:00
Elena Peña Tapia 884cfe6c66
Deprecate `bind_parameters` in favor of `assign_parameters` (#10792)
* Deprecate bind parameters

* Replace bind in docstring

* Test deprecation warning

* Remove bind_parameters in algorithms

* Update releasenotes/notes/deprecate-bind-parameters-283c94069e8a9142.yaml

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

* Apply suggestions from code review

* suppress warnings in test Parameter Expressions

* Add module to filter

* Add filter to context manager

* Fix black

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-09-12 14:43:40 +00:00
Simone Gasperini 7d17e6875d
Allow empty list default initialization for `SparsePauliOp` (#10765)
* Allow empty list default initialization of SparsePauliOp.from_list and SparsePauliOp.from_sparse_list

* Fix empty iterable comparison in SparsePauliOp list initialization

* Fix default arguments, internal checks, and error messages

* Add unit tests for SparsePauliOp empty iterable initialization

* Fix missing argument and linting errors

* Resolve minor changes requested by @ikkoham review

* Add release note with reference to issue #10159

* Edit release note as suggested by @jakelishman

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

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-09-12 13:36:56 +00:00
Jay Gambetta cd507adc68
Adding h, p and u to basic aer (#10673)
* Adding h, u and p to the BasicAer

* typo

* reno

* reno

* Update releasenotes/notes/h_basic_aer-3fc5e6776f0de9c1.yaml

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2023-09-08 15:15:41 +00:00
danielleodigie 031c0a24d2
Removal of deprecated property num_ancilla_qubits (#10793)
* Removal: Removing num_ancilla_qubits property from PolynomialPauliRotations class
removed function and deprecate_func from polynomial_pauli_rotations.py
added release note with upgrade notice

* Fixing release note to properly resolve property

* Fix release notes

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-09-07 21:37:14 +00:00
Elena Peña Tapia ebb11971c2
Fix `qpy` for multiple controlled parametrized gates (#10758)
* Add exception for controlled gate

* Add reno
2023-09-07 19:01:50 +00:00
Jake Lishman 3059193b2d
Add fast-path construction to `DAGCircuit` methods (#10753)
* Add fast-path construction to `DAGCircuit` methods

This optimises the constructor functions
`DAGCircuit.apply_operation_back`, `apply_operation_front` and `compose`
by giving callers a way to skip the validity checking when passing
known-good values.  In most cases when we're operating on the DAG, we
are certain that we're already upholding the invariants of the data
structure by nature of having a `copy_empty_like` or similar, and the
user should not pay a runtime price for what we should catch during
testing.

* Check for possibility of bits before iterating

---------

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
2023-09-07 18:29:28 +00:00
Jake Lishman c5c6b11324
Track Sabre decay heuristic on physical qubits (#10756)
The custom `decay` heuristic is supposed to penalise increases in depth
in the output.  The output space of qubits are the physical qubits, so
the depth is defined in relation to those.  Since its introduction in
gh-4537, this heuristic has instead been tracking the depth on the
virtual qubits, which due to the swaps is not necessarily related to the
depth in the output.

Notably, this commit actually makes the depth for routing large
volumetric circuits slightly _worse_ on average (at least for heavy-hex
topologies).  This may be because the effect on the heuristic is
overweighted, or that the depth tracking resets after each gate is
routed (and occasionally in between) to be flat across all qubits,
rather than reflecting the actual depth each qubit is subject to.
2023-09-07 12:53:08 +00:00
Matthew Treinish 838bb385b6
Use BasisTranslator for unroll 3q or more (#10776)
This commit modifies the the preset pass manager construction to by
default use the UnrollCustomDefinitions and BasisTranslator passes to
perform the unrolling of operations that operate on >= 3 qubits. This is
done by leveraging the min_qubits argument added to those passes in this
commit which lets you set a minimum number of qubit arguments to
translate operations for.

Previously, this was handled by the Unroll3qOrMore pass which works by
iterating over the DAG and finding all operations with >= 3 qubits and
recursively unrolling them until the output is all in terms of 1 or 2
qubit operations. This works fine, but has undesireable runtime
performance characteristics because standard gates repeatedly have to
build new DAGs to substitute in. For example, if you had a circuit with
50k CCXGates that would result in 50k new DAGs being created from
scratch for each instance of CCXGate. A previous attempt was made to
add a translation cache to that pass in #10703 but as was discussed in
code review caching the circuit is unsound as it's possible for a custom
gate object to be constructed such that it would be cached and return an
invalid substitution circuit. By leveraging the basis translator
we only build as many substition DAGs as needed.
2023-09-06 17:53:43 +00:00
Jake Lishman 3075f14d66
Handle final comments with no terminating newline in OpenQASM 2 (#10773)
* Handle final comments with no terminating newline in OpenQASM 2

Previously, if an OpenQASM 2 program to be parsed ended in a comment
with no terminating '\n', the lexer would fail to notice the end of the
file and would instead attempt to emit the second '/' of the comment
introduction as a 'Slash` token.

* Run `cargo fmt`

* Testing extra cases

---------

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

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-09-05 21:20:29 +00:00
Luciano Bello 8b0301058d
qiskit-terra == qiskit, in version libraries (#10425)
* __qiskit_version__ deprecation

* reno

* reno feature

* PackageNotFoundError

* revert stacklevel=2

* revert change in test

* remove OrderedDict

* other qiskit.__qiskit_version__  packages have their own __version__

* wording in the reno

* qiskit-terra == qiskit in version libraries

* lint

* readjust test

* raise an exception with a custom gate with no qubits or with one-or-more clbits

* QASM2ExportError

* test_circuit_raises_invalid_custom_gate_1

* test_circuit_raises_invalid_custom_gate_2

* reno

* revert

* revert

* adapt test

* reno

* conflicts
2023-09-01 21:11:08 +00:00
Jake Lishman e1fdb72322
Move OpenQASM 2 exporter to `qiskit.qasm2` (#10533)
* Move OpenQASM 2 exporter to `qiskit.qasm2`

This gets us into a position where the interface is similar between the
`qasm2`, `qasm3` and `qpy` modules (all of which do vaguely similar
things at an abstract level), which are in turn similar to functionality
in the Python standard libraries.

This commit simply moves the code from `QuantumCircuit.qasm` over to the
new location.  Some idiosyncrasies and additional bits of features that
we do not intend to support long term (e.g. formatted output) are not
brought over, but `QuantumCircuit.qasm` continues to perform those
jobs until it is deprecated and removed.

* Use 'text' instead of unknown 'qasm2' highlighter

* Fix lint import cycle

* Fix Sphinx typos

* Fix for new unitary decomposition

* Apply suggestions from code review

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

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2023-09-01 19:29:16 +00:00
Luciano Bello 89ea58b1f8
Support new-style Bit in Pauli convertor from QuantumCircuit (#10757)
* Do not use Bit.index in quantum_info/operators/symplectic/pauli.py

* bugfix

* Fix cross-reference

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-09-01 15:58:26 +00:00
Edwin Navarro 0a0e2627b2
Add display of internal circuits for ControlFlowOps to text drawer (#10414)
* Update text.py

* Update utils.py

* Fix test using text

* Lint

* Lint

* Fix if with body bug and first tests

* Finish tests

* Reno

* Output=text

* Cleanup

* Fix repr and repr_html issue with jupyter

* Cache _single_string to fix __repr__ and _repr_html__ issue

* Get circuits from blocks and fix inner_wire_map

* Fix gate on qubit issue and add test

* Lint

* First work on transpiled nested

* Fix condition for flow ops

* Intermediate flow_wire_map testing

* Fix clbit bug

* Finish transpiled bits bug

* Final fix for conditions and transpiles

* Fix review issues 1

* Revert wire_order test

* Fix control gates with wire_map and test changes

* Further case and else

* Fix review items 2
2023-08-29 16:21:16 +00:00
Ikko Hamamura 3bd1d46c93
Add validation to Sampler if there are no measurements (#10642)
* add validation

* Update qiskit/primitives/base/base_sampler.py

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

* add reno

* add test

* reversed iterate

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
2023-08-29 02:20:52 +00:00
abbycross cb4da68473
Typos flagged by the IBM Quantum Platform automatic spellchecker (#10711)
* typo

* typos

* typos

* typo

* typo

* typo

* typo

* typos

* typos

* typo

* typo

* typos

* typos

* typo

* typo

* typo

* typo

* typo

* typo

* typo

* typo

* typo

* typo

* typo

* typos

* typo

* typo

* typo

* typo

* typo

* typo

* rst!!!!!

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

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-08-26 12:57:18 +00:00
Paul Nation 676b329578
Keep resets at beginning of circuits (#10591)
* Keep resets at beginning of circuits

* Add reno and black

* Revert "Add reno and black"

This reverts commit ea7c1e683b.

* Add note back

* Add test over all transpile levels

* black

* Update releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml

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

* fix imports

* remove unused import

* damn variable names

* remove unused import

* conflict

* consolidate tests

* unrelated change

* Change release note to "upgrade"

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

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-08-24 14:02:36 +00:00
Matthew Treinish 4a8c0ca380
Migrate init stage to plugins (#10689)
This commit updates the preset pass manager construction to only use
plugins for the init stage. To accomplish this the previously hard
coded built-in pass manager used for each optimization level are
refactored to be in a plugin named "default". One thing that is changed
in this PR is that the use of `generate_control_flow_options_check()`
is moved to the `pre_init` stage. The reason for this is because the way
the init stage was being constructed in the preset pass managers was to
do initial checking of any methods, and this was unconditionally being
run. This is a more logical fit for pre_init stage because it should run
before any specified plugin.

Fixes: #10687
Fixes: #8661
2023-08-22 19:02:45 +00:00
Raynel Sanchez e7808e7b05
Optimization stage as a plugin. (#10581)
* Initial: Optimization stage as a plugin.

* CI: Added fix to preset_passmanager test

* Simplify inner translation stage creation logic

This commit changes the plugin construction logic slightly to adjust
how the embedded translation stage is created. After #10621 merged we
only need to use the plugin interface to get the translation stage pass
manager.

* Update documentation

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-08-22 16:06:38 +00:00
Matthew Treinish b0396870e2
Migrate layout stage to plugins (#10622)
* Migrate layout stage to plugins

This commit updates the preset pass manager construction to only use
plugins for the layout stage. To accomplish this the previously hard
coded built-in layout methods, trivial, dense, noise adpative, and
sabre are migrated to be exposed as built-in plugins. Additionally, the
special case of layout_method=None has been centralized into a standard
default method plugin, as the pass construction in this case involved
extra steps for each optimization level. This simplifies the preset pass
manager construction as now the layout stage is solely built via
plugins.

Fixes #9455

* Remove unnecessary if statement

* Handle invalid optimization levels in plugins

* Remove unused variable post-rebase
2023-08-22 11:25:08 +00:00
Matthew Treinish e6c431e306
Fix performance of Sabre rust<->Python boundary (#10652)
* Fix performance of Sabre rust<->Python boundary

In #10366 the SabreLayout and SabreSwap passes were refactored to
support nested control flow blocks. As part of that refactor a new
struct SabreResult was created to store the nested results for each
block. This new class however resulted in PyO3 cloning the full swap map
on every access. Since we have at least 1 access per gate in the circuit
(and another one for each swap) this extra clone() adds a lot of extra
overhead for deep circuits. In extreme cases this regression could be
quite extreme. To address this the result format is changed to be a
tuple (as it was originally), while this is less ergonomic the advantage
it provides is that for nested objects it moves the rust object to the
pyo3 interface so we avoid a copy as Python owns the object on the
return. However, for control flow blocks we're still using the
SabreResult class as it simplifies the internal implementation (which is
why #10366 introduced the struct). The potential impact of this is
mitigated by switching to only a single clone per control flow block,
by only accessing the SabreResult object's attribute on each recursive
call. However, if it is an issue in the future we can work on flattening
the nested structure before returning it to python to avoid any clones.

Fixes #10650

* Simplify recursive call logic in _apply_sabre_result

This commit simplifies the logic in the recursive call logic in
_apply_sabre_result to always use a tuple so we avoid an isinstance
check.

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

---------

Co-authored-by: Kevin Hartman <kevin@hart.mn>
2023-08-17 15:23:45 +00:00
Alexander Ivrii 3fcd145ee1
constructing cliffords from linear functions and permutation gates (#10423)
* constructing cliffords from linear functions and permutation gates

* updating test
2023-08-16 13:35:22 +00:00
Luciano Bello 287ac5c18a
Fix classical-synthesis label ordering with `registerless=False` (#9536)
* follow the Tweedledum convention on endianness

* reno

* add test

* optional dep

* docstring

* reno

* attempt to fix sphinx

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2023-08-16 12:02:30 +00:00
atharva-satpute fe87015a90
Reject bad values in `SparsePauliOp.paulis` setter (#10437)
* Fix Sparse pauli setter to update dimension info

* Fix Sparse pauli setter to verify dimension info

Value error will be raised if:
1. Number of qubits are not equal
2. Number of elements in PauliList are not equal

* Add tests

* Add release note

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
2023-08-16 06:55:23 +00:00
Jay Gambetta 213580d2fb
Fixing the tools for plotting Pauli vec (#10619)
* fixing the plot for pauli_vec to scaled to pm 1

* testing

* linting

* ref figure

* Update docstring to define Paulivector

* add reno

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2023-08-15 15:50:34 +00:00
Matthew Treinish 8a180ee8d4
Move metapackage shim for combined releases (#10530)
* Move metapackage shim for combined releases

Now that Qiskit 0.44.0 has been released, the Qiskit project is now what
was formerly qiskit-terra. However, because Python packaging lacks a
clean mechanism to enable one package superseding another we're not able
to stop shipping a qiskit-terra package that owns the qiskit python
namespace without introducing a lot of potential user friction. So
moving forward the qiskit project will release 2 packages an inner
qiskit-terra which still contains all the library code and public facing
qiskit package which installs that inner package  only. To enable this
workflow this commit migrates the metapackage setup.py into the terra
repository and setups build automation to publish a qiskit package in
addition to the inner terra package on each release tag.

* some follow up on https://github.com/Qiskit/qiskit-terra/pull/10530 (#19)

* some follow up on https://github.com/Qiskit/qiskit-terra/pull/10530

  * extend some badges
  * This Qiskit contains the building blocks for creating and working with quantum circuits, programs, and algorithms. -> This framework allows for building, transforming, and visualizing quantum circuits.
  * The explanation of the Bell state is moving to IBM Quantun learning platform
  * I think examples/ should eventually be replaced by proper tutorials
  * Add StackOverflow as a forum
  * Remove link to https://github.com/Qiskit/qiskit-tutorials

* Update README.md

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

* Update README.md

* Update README.md

* broken lines in badges

* doi

---------

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

* Expand lint checks to entire qiskit_pkg dir

* Unify extras in terra setup.py

* Update CI lint job

* Remove unused json imports

* Cleanup manifest file

* Finish comment

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2023-08-15 11:57:23 +00:00
Alexander Ivrii 242b3c0ee9
Adding ``coupling-map`` and ``target`` to ``HighLevelSynthesis`` (#10477)
* extending HighLevelSynthesis and HighLevelSynthesisPlugin interface with target and coupling_map

* improving docstrings and adjusting arguments to implemented plugins

* adding test that the coupling map gets passed correctly

* release notes

* docs

* using DAGCircuit's find_bit

* removing debug print

* updating plugin interface docs

* improvements to release notes

* removing unused variable

* adding use_qubit_indices; updating release notes and tests

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

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

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

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

* Update qiskit/transpiler/preset_passmanagers/common.py

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

* Update qiskit/transpiler/preset_passmanagers/common.py

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

* Update qiskit/transpiler/preset_passmanagers/common.py

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

* Update qiskit/transpiler/preset_passmanagers/common.py

* setting coupling_map to None

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-08-11 20:36:25 +00:00
Jay Gambetta 77801c8baf
Cleaning up U3 in the unitary extension (#10597)
* Clean up to use U vs U3

Removing U3 from unitary and moving it to the U gate

* fixing test

* Create unitary-u-not-u3-0a32c2d968f7890e.yaml
2023-08-10 12:49:15 +00:00
Jake Lishman 06416d7ee7
Fix multiple nested custom controlled gates in QPY (#10537)
* Fix multiple nested custom controlled gates in QPY

When a circuit contained multiple custom controlled gates that in turn
had custom definitions, the QPY serialisation could fail to write out
some of the inner instructions correctly.  This led to an invalid QPY
file that could not be read back.

* Remove local warning-suppression import
2023-08-07 15:07:06 +00:00
Diego Emilio Serrano d7f02a61ab
Add `draw` method to `Operator` class (#10271)
* add draw method to Operator class

* add _ipython_display_ to operator class

* (fix) check type of state in TextMatrix to allow the use of Operators

* add Operator drawer tests

* eblack, elint changes

* add reno

* (fix) replace repr output, change ValueError to f-string

* (fix) remove duplicate 'latex' option in test_operator

* fix lint, build errors

* add condition to TextMatrix to hide dims for qubit operator

* (fix) remove elif statement in TextMatrix to avoid unhandled else branch
2023-08-04 17:21:59 +00:00
Jake Lishman 290305a2b0
Update minimum Rust version to 1.64 (#10541)
Raising the minimum Rust version lets us access workspace dependencies,
which are a convenient way of managing shared metadata between the
different crates in the project, which deduplicates a good amount of
our metadata.  This also lets us share the PyO3 version and minimum
feature set between crates, reducing the number of places that need to
be updated on a Python version bump.

`Cargo.lock` is completely regenerated for this commit with the new
unification, with the minor tweak of having run

        cargo update -p 'indexmap@2.0.0' --precise '1.9.3'

This is required to unify the `hashbrown` versions down to 0.12.3
between our dependencies and `pyo3`, which otherwise transitively
depends on `hashbrown ^0.14` via pulling in `indexmap 2.0`.  This caused
a build failure, since the `hashbrown` types that PyO3 adds `impl`s of
its traits to are not the same types that our extension modules attempt
to use with it.
2023-08-03 14:13:44 +00:00
Abhiraj Shrotriya 4372c6d42a
Implemented a type check in copy method of QuantumCircuit class (#10521)
* Implemented a type check in copy method of QuantumCircuit class

* Made copy method code more efficient and added a circuit operation test

* Corrected and made clear documentation of copy method - QuantumCircuit

* Fix wording

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-08-03 11:50:24 +00:00
Jake Lishman 4722c50a59
Force decimal points in OpenQASM 2 floats (#10532)
* Force decimal points in OpenQASM 2 floats

The letter of the OpenQASM 2 specification has a regex defining
floating-point literals that requires a decimal point, even in the
presence of an exponential component.  This is unusual for most
programming languages, but Qiskit's exporter should follow the spec as
close as we can to increase interop.  Our parser accepts floats with an
exponent and no decimal point as a minor syntax extension, unless in
strict mode.

* Simplify English
2023-07-31 16:05:13 +00:00
Jake Lishman 9ae6164323
Add release note for `Expr` support (#10503)
* Add release note for `Expr` support

* Fix role typo
2023-07-27 13:45:30 +00:00
Elena Peña Tapia f01b7ab8eb
Update algorithms deprecation message/reno (#10500)
* Update reno

* Update deprecation warning
2023-07-26 09:55:16 +00:00
Alexander Ivrii 07b06f9a0d
limiting matrix-based commutativity check (#10495)
* limiting matrix-based commutativity check

* adding tests with the order of gates fixed

* lint tweaks

* improved released notes
2023-07-25 12:08:26 +00:00
Matthew Treinish 42a0ee84df
Fix final_layout when VF2PostLayout finds a better layout (#10466)
* Fix final_layout when VF2PostLayout finds a better layout

This commit fixes a bug in the preset pass managers when VF2PostLayout
is run and finds a better layout to use. In these cases the ApplyLayout
was updating the layout but we never updated the final layout to reflect
these changes. This would result in an incorrect final layout because
the input positions of the qubits were incorrect after re-applying the
layout. This commit fixes this by adding code to ApplyLayout to also
update final_layout, if one is set, to reflect the new initial layout
found by VF2PostLayout.

Fixes #10457

* Remove stray debug print

* Use a list instead of a dict

* Add assertion on vf2postlayout being used in compiler.transpile tests

* Actually assert a post layout is set
2023-07-24 21:18:58 +00:00
Jake Lishman e75893d455
Fix empty-barrier handling in OpenQASM 2 (#10469)
The new parser would allow a `barrier;` statement, implicitly
broadcasting it across all qubits in scope.  This is technically not
supported by the OpenQASM 2 specification, but is a useful
quality-of-life extension to the specification (in the same way that
Qiskit interprets barriers, and the OpenQASM 3 specification defines the
`barrier;` statement).  The precise rule is added to the new parser's
`strict` mode.

The OpenQASM 2 _exporter_ similarly should not have been putting out
`barrier;` statements.  These could only occur in Qiskit when a barrier
was explicitly constructed with zero elements (as opposed to the call
`QuantumCircuit.barrier()`, which has the all-in-scope behaviour), and
consequently have no actual meaning or effect.  The exporter is modified
to simply skip such instructions, for as long as Qiskit permits the
qubitless barrier statement.
2023-07-24 20:04:05 +00:00
TsafrirA 802a735ebe
Fix Pulse channel index validation (#10476)
* Correct channel index validation

* Add tests and release note.
2023-07-24 12:32:04 +00:00
Luciano Bello 208c29a649
raise an exception with a custom gate with clbits or no qubits (#10438)
* raise an exception with a custom gate with no qubits or with one-or-more clbits

* QASM2ExportError

* test_circuit_raises_invalid_custom_gate_1

* test_circuit_raises_invalid_custom_gate_2

* reno

* Split error messages to be more specific

* Fix testing bug

* Fixup release note

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-07-24 11:05:38 +00:00
Matthew Treinish 2710765293
Revert "Revert "Pass manager refactoring: add passmanager module (#10124)" (#10454)" (#10474)
This reverts commit c03e4c78bc.
2023-07-22 12:55:07 +00:00
Matthew Treinish a8faffb120
Set version number to 0.25.0rc1 for first release candidate (#10451)
For the 0.25.0 release we're going to push release candidates prior to
the release to enable testing before we cut the final release. In
preparation for tagging the first release candidate this commit updates
the version string to indicate it's a release candidate. This commit
should be what gets tagged as 0.25.0rc1.
2023-07-21 14:32:47 +00:00
Kevin Hartman 4737e87ca5
Allow circuits w/ control flow in O2 and O3 (#10372)
* Allow control flow in opt levels 2 and 3.

* Add release note.

* Enable testing for opt 2 and 3.

* Remove guard on translation_method='synthesis'.

* Fix test for synthesis guard.

* Skip o3 qpy full path transpile test on windows

In CI we're seeing a reliable failure on windows when scipy is calling
LAPACK. This appears to be unrelated to the change in this PR branch and
is isolated to specific windows environments. This commit adds a skip
condition to skip that one test to workaround the failure in CI. The
wider issue with scipy compatibility on windows is being tracked in
issue #10345, when we have a conclusion to that and can reliably run
this test we should remove this skip condition.

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-07-21 12:02:17 +00:00
Raynel Sanchez 2b225d3713
Optimize `ConsolidateBlocks` pass (#10365)
* Initial: Introducing speedup by calculating matrix

* Lint: Reformat using Black

* Fix: Added `basis_count` and `outside_basis`

* Fix: Use `Operator` if `to_matrix` is unavailable.

* Fix: Default to Operator when necessary
- Will default to previous method when blocks have more than 2 qubits.
    - This is a temporary measure.

* Lint: Removed Cyclic import

* Docs: Added release note.

* Docs: Added reference to the issue.

* Fix: Move `block_to_matrix` to ~.passes.utils

* Lint: Fixed cyclical import and order

* CI: Removed type checking

* Add: Exceptions on `_block_to_matrix`

* Docs: Fix release note.

* Fix: Change import path for block_to_matrix

* Update qiskit/transpiler/passes/utils/block_to_matrix.py

---------

Co-authored-by: ewinston <ewinston@us.ibm.com>
2023-07-20 22:35:25 +00:00
Kento Ueda ac29776243
Fix UnassignedDurationError of update_from_instruction_schedule_map (#10447)
* fix UnassignedDurationError of update_from_instruction_schedule_map

* add test

* add reno

* rename test

* fix reno

* Update releasenotes/notes/fix-update-from-instruction-schedule-map-d1cba4e4db4b679e.yaml

---------

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2023-07-20 18:48:42 +00:00
Jake Lishman d13f0bbad6
Add `Expr` support to OpenQASM 3 exporter (#10408)
* Add `Expr` support to OpenQASM 3 exporter

This adds support for `Expr` nodes in `condition` fields and
`SwitchCaseOp.target`.  The general `c_if` condition checking is lifted
into an `Expr` node as part of the OQ3 export, so the form of them
automatically becomes like the new-style outputs, depending on how
`expr.lift_legacy_condition` chooses to raise them to `Expr` nodes.

As part of the refactor of the `Expression` subtree of the temporary
AST, I removed `SubroutineCall`.  Its definition was severely
out-of-date (a form from before even the initial arXiv draft), where it
was statement-like instead of expression-like.  There is currently no
support in Qiskit for representing these sorts of subroutines properly,
and the OQ3 exporter would produce invalid OQ3 if it encountered
something that it thought should be a a subroutine call.  This commit
fixes that bug, correctly raising an exception that non-unitary
instructions are not yet supported for export.

This commit also removes the special casing from the `CXGate` into the
exporter itself; it was more convenient in the new structure of some
internal components, and it's a data model we don't want to support
anyway.

* Use `IntegerLiteral` for `Uint` values

This is what the QSS stack expects (they don't like bitstring literals
in expressions yet), and is more in line with what we used to do anyway.

* Fix quotes

* Add test of no spurious casts
2023-07-20 17:58:20 +00:00
John Lapeyre e56c1b4420
Support control flow in ConsolidateBlocks (#10355)
* Support control flow in ConsolidateBlocks

* Add release note for support control flow in ConsolidateBlocks

* Move imports from inside function to top level

* Make construction of ConsolidateBlocks for control flow ops more efficient

* Do IfElseOp test without builder interface

Before, we used the builder interface for an ifelse op. Some details of
the circuit built, in particular the mapping of wires is not deterministic.
We could have used canonicalize_control_flow. But instead we construct the
IfElseOp manually. This removes the complexity of the builder interface from
this test.

* Linting

* Avoid cyclic import

* Try to fix cyclic import (in lint tool only)

* Reuse top-level consolidation pass and add tests

* Before, we created an new ConsolidationPass when descending into control flow
  blocks. With this commit, we use the existing pass.

* Add some tests for cases where consolidation should not happen.

* Remove argument `decomposer` from constructor of ConsolidateBlocks

This was added in a previous commit in the series of commits for this
PR. The code has been redesigned so that this argument is no longer
necessary.

* Remove cruft accidentally left

In the first version of the associated PR, we created a new pass
when descending into control flow blocks. These lines were included to
support that construction and are no longer needed.

* Move function-level import to module level

Remove unused import in tests

* Write loop more concisely

* Update releasenotes/notes/add-control-flow-to-consolidate-blocks-e013e28007170377.yaml

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

* Use assertion in tests with better diagnostics

* Remove reference to decomposer from docstring to ConsolidateBlocks

The previous doc string was a bit imprecise. It also referred to a decomposer which although
implied, is not meant to be accessible by the user.

* Use more informative tests for ConsolidateBlocks with control flow

* Simplify test in test_consolidate_blocks and factor

* Gates used in testing ConsolidateBlocks with control flow ops were copied
from another test in the file. They complicate the test, and removing them does
not weaken the test at all.

* Factor some code within a test into a function

* Factor more code in test

* Use clbit in circuit as test bit when appending IfElse

This has no effect on the test. But, previously, we used a clbit taken
from an unrelated circuit. This might give the impression that there is
some significance to this unexpected choice.

* In test, use bits in circuit as specifiers when appending gate to that circuit

Previously we used qubits and clbits from an unrelated circuit to specify which
bits to apply an IfElse to when appending. Here, we use bits from the same circuit that we are
appending the gate to. This does not change the test. But again, one might look for
significance in the previous unusual choice.

Qiskit considers two registers of the same length and the same name to be the
same register. The previous behavior depended on this choice.

* In a test, don't use qubits from unrelated circuit when constructing circuit

This has no effect on the test. As in the previous commits, the choice was
unusual and might imply some significance. The more natural choice is to
create new qubits by specifying the number.

* Factor code in test to simplify test

* Simplify remaining control flow op tests for ConsolidateBlocks

These simplifications are similar to those made for the first test.

* Run black

* Update test/python/transpiler/test_consolidate_blocks.py

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

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-07-20 17:29:51 +00:00
Edwin Navarro 9a78e11528
Add display of internal circuits for ControlFlowOps to mpl circuit drawer (#10207)
* Remove deprecated args from mpl drawer

* Reno mod

* Convert to wire_map, node_data, etc

* Lint

* Minor changes to match flow changes

* Cleanup

* Fix layer width per node and comments

* Lint

* Adjust layer num loading

* Revert n_lines

* Lint

* Add glob_data

* Lint and cleanup

* Initial PR for if-else

* Unused arg

* Lint

* Iniital box fold

* Fold flow boxes

* Add reno

* Fix initial mpl and window load

* Move figure, mpl, and style info to draw()

* Comments

* Change font vars and fix ax

* Make patches_mod global

* Minor fixes after pre merege

* Lint

* Add while

* Add for loop

* Finish SwitchCase and cleanup and utils gate_span

* Cleanup

* Fix gate_span bug and comments

* Fix layer bug by using all qubits in _get_layered

* Added final release note and deleted old one

* Minor spacing changes

* Add ipynb/mpl/circuit tests and references

* Lint

* Minor comments

* Adjust for_loop test

* Add test for IfElseOp with body

* Lint

* Update state_city image

* Comments, PORDER changes, cleanup

* Adjust MASK zorder

* Fix text color issue with other styles

* Final fixes
2023-07-20 17:11:53 +00:00
Matthew Treinish c03e4c78bc
Revert "Pass manager refactoring: add passmanager module (#10124)" (#10454)
This reverts commit fbd64d95d9. The follow
on PR to this one #10127 which is making internal refactors to the pass
manager code now that's it a standalone module is still undergoing
active review and the scope of the PR is sufficiently large that it
likely won't be viable for the pending 0.25.0 release. This commit
temporarily reverts #10124 which was the first step of creating a module
by porting the pass manager code in it's current form to a standalone
module so that we're not committed to the API as part of the 0.25.0
release to give more time for #10127 to finalize what the eventual
`qiskit.passmanager` API will look like.

This revert should itself be reverted after 0.25.0rc1 is tagged and
the main branch opens up for 0.45.0 development. As this revert is
not an indication that we did not want #10124 it's just to avoid
committing to the API prematurely.
2023-07-20 16:41:51 +00:00
Matthew Treinish fcd7766fec
Add flatten option to the NLocal family (#10269)
* Add flatten option to the NLocal family

This commit adds a new flag `flatten` to the circuit library elements in
the NLocal family. This flag is used to avoid the nested wrapping of the
output that is done by default in the output of these gates. This is
done primarily in the interest of performance. The runtime
performance of bind_parameters() is vastly improved with a flattened
output compared to the nested object. For example, running:

```
qc = EfficientSU2(100, entanglement="linear", reps=100)
qc.measure_all()
qc.bind_parameters({x: math.pi / 2 for x in qc.parameters})
```

the runtime of `bind_parameters()` went from ~390 seconds with the
wrapped output to ~0.5 seconds with the flattened output. I think given
these results longer term we might want to flip the default behavior to
only wrap on user request (likely for visualization as that's the only
use case I can think of for the wrapped output). The default value
is set to `None` in this PR to facilitate this change. In 0.26/0.45 we
can emit a warning if `flatten` is `None` to warn that the default will
change in a future release.

* Add missing nlocal subclasses

* Add setter

* Fix lint

* Fix flatten for EvolvedOperatorAnsatz
2023-07-20 16:08:56 +00:00
Jake Lishman 7c1b8ee4fe
Improve parameter-binding performance of large instructions (#10284)
* Improve parameter-binding performance of large instructions

Previously, the parameter-assignment methods of `QuantumCircuit` had
poor performance when an instruction had a complex definition that
involved many of the parameters being bound.  The strategy of binding
each parameter separately led to each definition being copied and
rebound multiple times, with each rebinding being recursive all the way
down.

This commit makes the definition rebinding happen only once per
instruction, and updates the data model used to make it a complete
recursion through `QuantumCircuit.assign_parameters`.  This has the side
effect of fixing an issue where internal global phases would not be
updated.

The algorithmic change that enables this (just rebind the definition at
the end) is rather simpler than the length of this patch suggests.  This
is just because the previous structure of separating out a single
`_assign_parameter` method made it harder to restructure the logic
without introducing unpleasant stateful coupling between the driver and
helper methods.  Instead, I inlined most of the helper functions into
the driver body, so we can treat some components of the binding in a
per-parameter way and some in a per-operation way, in whatever way is
better.

* Fix lint

* Reduce overhead from input normalisation

This reduces several costs in the input normalisation, and makes the
calculation of some properties lazy for the sequence-like inputs; for
many close-to-hardware circuits such as those used in PEC, the sequence
form of parameter input is more natural, and almost no instructions will
have internally parametrised definitions, nor will there be a
parametrised global phase or calibrations.  In these cases, we can avoid
overhead from eagerly normalising the input into the forms that's easier
for these less-common assignment operations to use.

As a side-effect of the abstraction, we can also avoid making several
dictionary copies, and just use the mapping abstraction to filter the
dictionary during iteration on the fly.

This also takes the opportunity to improve the performance of sorting
large vectors of parameters.  In practice, I don't think this had a huge
impact on performance, but in principle it's rather more efficient now
and results in many fewer Python function calls during a sort.

* Address Ruff's generator concern

* Add comment on new keyword arguments
2023-07-20 14:46:47 +00:00
Elena Peña Tapia 2616602a54
Add deprecation warning to algs module (#10406)
* Add deprecation warning to algs module

* Apply suggestions from code review

Co-authored-by: Eric Arellano <14852634+Eric-Arellano@users.noreply.github.com>

* Add link to repo

* Add release note

* Add migration guide to release note

* Apply suggestions from code review

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

---------

Co-authored-by: Eric Arellano <14852634+Eric-Arellano@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
2023-07-20 13:58:46 +00:00
Alexander Ivrii 94cb65e97f
Add block collection options `split_layers` and `collect_from_back` (#10254)
* adding reverse collection direction and test

* propagating options to CollectAndCollapse, CollectLinearFunctions and CollectCliffords passes

* reno

* test for clifford collection pass

* adding option split_layers

* propagating options and adding tests

* imrpoving tests and release notes

* temporarily removing release notes

* reinstating release notes

* reno fix

* change suggestion in review comments

* correct fix this time

* using condition_resources instead of condition_bits

* Update qiskit/dagcircuit/collect_blocks.py

This is nice!

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-07-20 12:36:25 +00:00
Junya Nakamura e5950661a5
Add in qpy the support for Discriminator and Kernel (#10327)
* add support for Discriminator and Kernel

* make Kernel and Discriminator hashable

* correct _assert_nested_dict_equal()

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

* ensure b does not have extra keys

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

* devide _read_kernel_and_discriminator and _write_kernel_and_discriminator

* update docs

* add tests testing Kernel/Discriminator equality

* add a qpy compatibility test

* add releasenote

* improve hashing in Kernel/Discriminator

* rm hashing from Kernel/Discriminator

* use write/read_sequence() to serialize lists

* add (de)serializer for dict and list

---------

Co-authored-by: Will Shanks <wshaos@posteo.net>
Co-authored-by: Will Shanks <willshanks@us.ibm.com>
2023-07-20 09:46:14 +00:00
Jake Lishman 10e66ff698
Add `Expr` support in `DAGCircuit.substitute_node` (#10382)
As part of this minor refactor, this updates the logic to no longer
silently override conditions on the replacement `op`.  The method gains
a `propagate_condition` argument analogous to the same argument in
`substitute_node_with_dag`, which can be set `False` to specify that the
caller is aware that the new operation should implement the same
conditional logic.
2023-07-20 00:23:53 +00:00
Kento Ueda f492c450a7
Add a new argument concurrent_measurements to target class (#10258)
* fix measure_v2

* modify measure_all

* dispatch backend

* add test of the builder with backendV2

* reconfigure test codes and some func

* refactoring

* add reno

* fix _measure_v2

* fix backend.meas_map in measure_v2

* fix reno

* delete get_qubit_channels from utils

* add get_qubits_channels in qubit_channels

* recostruct test about the builder with backendV2

* add meas_map to Target class

* fix after mergin main branch

* fix documents about meas_map

* format target.py

* add reno

* add meas_map to target in convert_to_target

* add the more description about meas_map

* Update releasenotes/notes/enable_target_aware_meas_map-0d8542402a74e9d8.yaml

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

* fix test_meas_map

* remove format_meas_map

* rename meas_map in target to concurrent_measuments

* change reno

* remove Unused Union Dict

* concurrent_measurements set as getattr(configuration, meas_map)

* Update qiskit/transpiler/target.py

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

* Update qiskit/transpiler/target.py

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

* format

---------

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2023-07-20 00:15:50 +00:00
Luciano Bello d97f80518b
__qiskit_version__ deprecation (#10242)
* __qiskit_version__ deprecation

* reno

* reno feature

* PackageNotFoundError

* revert stacklevel=2

* revert change in test

* remove OrderedDict

* other qiskit.__qiskit_version__  packages have their own __version__

* wording in the reno

* lint

* Update qiskit/tools/jupyter/version_table.py

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

* Update qiskit/tools/jupyter/version_table.py

* Restore removed version checks

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-07-19 23:23:43 +00:00
Zain Mughal ba6b9e409f
Add find_bit method to DAGCircuit to get mapping of bits to positional index (#10128)
* Added locate_bit method

* Changed transpilers passes to use find_bit method

* New changes, still need to fix

* Adding find_bit method to transpiler passes

* Added DAGCircuit method to get mapping of Qubit and Clbit to positional index Issue#9389

* added release notes for issue#9389

* fixed some formatting issues

* fixes for run, lint and doc errors

* updated releasenote and bip_model.py

* variable fix in bip_model.py

* reverted changes of bip_model.py

* revised files for updated usage of find_bit

* added changes to files noted

* Add test coverage

* Update releasenotes/notes/add-method-for-mapping-qubit-clbit-to-positional-index-6cd43a42f56eb549.yaml

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-07-19 20:10:21 +00:00
Jake Lishman 9a46c5af32
Add `Expr` support to the control-flow builders (#10400)
* Add `Expr` support to the control-flow builders

This is generally relatively straightforwards; anywhere where we examine
the resources used by an operation, we need to update to account for
classical resources potentially being tied up in `ControlFlowOp` fields
in `Expr` nodes as well.

This also has the side effect of fixing a bug where a nested
`SwitchCaseOp.target` wasn't considered in the scope building for _all_
control-flow operations, which could incorrectly cause some registers to
be missed in outer scopes.

* Remove out-of-date comment
2023-07-19 18:50:13 +00:00
Matthew Treinish 346ca77438
Remove list argument broadcasting and simplify transpile() (#10291)
* Remove list argument broadcasting and simplify transpile()

This commit updates the transpile() function to no longer support
broadcast of lists of arguments. This functionality was deprecated in
the 0.23.0 release. As part of this removal the internals of the
transpile() function are simplified so we don't need to handle
broadcasting, building preset pass managers, parallel dispatch, etc
anymore as this functionality (without broadcasting) already exists
through the transpiler API. Besides greatly simplifying the transpile()
code and using more aspects of the public APIs that exist in the
qiskit.transpiler module, this commit also should fix the overhead we
have around parallel execution due to the complexity of supporting
broadcasting. This overhead was partially addressed before in #7789
which leveraged shared memory to minimize the serialization time
necessary for IPC but by using `PassManager.run()` internally now all of
that overhead is removed as the initial fork will have all the necessary
context in each process from the start.

Three seemingly unrelated changes made here were necessary to support our
current transpile() API without building custom pass manager
construction.

The first is the handling of layout from intlist. The
current Layout class is dependent on a circuit because it maps Qubit
objects to a physical qubit index. Ideally the layout structure would
just map virtual indices to physical indices (see #8060 for a similar
issue, also it's worth noting this is how the internal NLayout and QPY
represent layout), but because of the existing API the construction of
a Layout is dependent on a circuit. For the initial_layout argument when
running with multiple circuits to avoid the need to broadcasting the
layout construction for supported input types that need the circuit to
lookup the Qubit objects the SetLayout pass now supports taking in an
int list and will construct a Layout object at run time. This
effectively defers the Layout object creation for initial_layout to
run time so it can be built as a function of the circuit as the API
demands.

The second is the FakeBackend class used in some tests was constructing
invalid backends in some cases. This wasn't caught in the previous
structure because the backends were not actually being parsed by
transpile() previously which masked this issue. This commit fixes that
issue because PassManagerConfig.from_backend() was failing because of
the invalid backend construction.

The third issue is a new _skip_target private argument to
generate_preset_pass_manager() and PassManagerConfig. This was necessary
to recreate the behavior of transpile() when a user provides a BackendV2
and either `basis_gates` or `coupling_map` arguments. In general the
internals of the transpiler treat a target as higher priority because it
has more complete and restrictive constraints than the
basis_gates/coupling map objects. However, for transpile() if a
backendv2 is passed in for backend paired with coupling_map and/or
basis_gates the expected workflow is that the basis_gates and
coupling_map arguments take priority and override the equivalent
attributes from the backend. To facilitate this we need to block pulling
the target from the backend This should only be needed for a short
period of time as when #9256 is implemented we'll just build a single
target from the arguments as needed.

Fixes #7741

* Fix _skip_target logic

* Fix InstructionScheduleMap handling with backendv2

* Fix test failure caused by exception being raised later

* Fix indentation error

* Update qiskit/providers/fake_provider/fake_backend.py

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

* Fix standalone dt argument handling

* Remove unused code

* Fix lint

* Remove duplicate import in set_layout.py

A duplicate import slipped through in the most recent rebase.
This commit fixes that oversight and removes the duplicate.

* Update release notes

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

* Adjust logic for _skip_transpile to check if None

* Simplify check cmap code

* Only check backend if it exists

---------

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-07-19 16:38:14 +00:00
John Lapeyre 539557d941
Remove method `qasm` from `Instruction` and all of its subclasses (#10399)
* Deprecate Instruction.qasm

* Deprecate all `qasm` methods for Instruction and subclasses.
* Move code for generating OpenQASM 2 strings to `QuantumCircuit`.
* Test that deprecation warnings are raised.
* Add release note.

* Fix lint errors

* Fix still more lint errors

* Revert replacing old code with new inside deprecated method

In x.py in class C3SXGate the method `qasm` has been deprecated. It's
ok and simpler to deprecated code in this method. The two deprecated
pieces will be removed together.

* Revert formatting change

`for (param, value) in ...` was replaced with `for param, value in ...`.
This commit reverts that change.

* Remove method has_qasm2 from HamiltonianGate and simplify a deprecation message

* The method has_qasm2 was added in a previous commit (not in main). It is
  removed with this commit.

* An additional message was added to the deprecation warning for HamiltonianGate.qasm.
  It is removed with this commit

* A test has been updated to reflect these changes.

* Simplify hack for name c3sqrtx

c3sqrtx is the name we need to use with OpenQASM2 for qiskit's c3sx.
This makes the hack a bit less wordy and perhaps more palatble. The gate's
name is no longer changed before calling a function on it, then changed back.

* Remove intermediate variable introduced with this 10399

PR 10399 (not merged) changed a method call inside a Python f-string statement
into a call outside, introducing a variable, and use of that variable inside the
f-string. This commit makes a more minimal change.

Now we only replace the method call with an ordinary function call.

* Restore blank line inadvertently removed

* Factor out creation of "custom" qasm2 operation statement

* Remove addition_message from deprecation in x.py

* Update documentation for error thrown by QuantumCircuit.qasm

The docstring states that a CircuitError is raised if a gate cannot be converted to qasm2.
But this is now handled ultimately by the qasm2 exporter.

* Rename variable from name_param to qasm2_call

* Update call from QasmError to QASM2ExportError

* Remove unused import
2023-07-19 06:21:16 +00:00
Caleb Johnson 665f1dd8ee
Add separable_circuits method to DAGCircuit class (#9471)
* Add decompose_dag method to DAGCircuit class

* Don't clean up idle wires within function

* Add tests for DAGCircuit.separable_circuits

* Add ordering and QuantumCircuit equivalency tests. Add release note.

* Code style changes

* Update release note

* Clean up documentation

* Return a DAG for any partition with at least one qubit, even if empty

* Adjust tests to new flag

* peer review

* peer review

* fix var name

* test against dagcircuits

* lint

* test remove_idle_wires

* improve release note

* Update separable_circuits docstring

* Sort the dag circuits in tests to prevent them breaking in future

* minor cleanup

* minor cleanup

* Fix sorting

* Fix type-hint resolution

* black

* unused import

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-07-19 06:18:48 +00:00
Kevin Hartman 026d60a733
Enable Sabre for control flow circuits at O1 (#10371)
* Enable Sabre for control flow circuits in O1.

* Add release note.

* Update preset pass manager tests.
2023-07-19 06:16:09 +00:00
Kevin Hartman 49b383a978
Support control flow in `SabreSwap` and `SabreLayout`. (#10366)
* Initial commit.

* Downgrade hashbrown to 0.12.3 for compat with Rustworkx.

* Implement gen_swap_epilogue.

* Add Python wrappers for structs.

* Implement DAG -> SabreDAG.

* Apply block results in sabre_swap.py.

* Fix node ID lookup issue.

Previously, we were using original DAG node IDs to look up nodes
in the expanded nested DAGs, but these IDs are of course not the
same.

* Fix bug where block circuits started out non-empty!

* Move DAG building and result application to functions.

* Implement control flow handling for Sabre layout.

* Fix qreg indexing bug for new swaps versus routed gates.

* Run Python formatting.

* Fix bug where root_dag was used instead of mapped_dag.

* Fix bug where swap_epilogue was in terms of physical bits instead of logical.

* Add more tests from stochastic swap.

* Fix bug mapping inner block qubits to outer circuit qubits.

* Update sabre swap testing.

* Update TODOs.

* Fix bug where a 2Q CF nodes would be mistakenly added to the extended set.

* Port more testing from stochastic swap.

* Run formatting.

* Port remaining stochastic swap tests.

* Mark Sabre routing and layout as known good for CF.

* Add random circuit valid output testing for Sabre.

* Run cargo fmt.

* Fix lint issues.

* Fix lint issues.

* Update 'test_invalid_methods_raise_on_control_flow'

* Make gen_swap_epilogue consume 'from_layout'.

* Add release note.

* Update TODO comment about num_qubits.

* Add comment about forward DAG.

* Explicitly mark NodeBlockResults as a mapping.

* Use closure instead of lambda noun.

* Add comment to make gate placement handling clearer.

* Use hashbrown::HashMap in SabreDAG.

* Add caching of circuit_to_dag.

* Simplify parameters to _build_sabre_dag.

- Makes it more explicit that the num_qubits used in a SabreDAG
  should be the number of physical qubits on the device.
- We no longer pass clbit indices because they are always local to
  the block, i.e. there's no current reason for them to be consistent
  across the root DAG and inner blocks, like we must do for qubits.

* Copy cregs during empty_dag.

* Comment-out assert.

* Use intersection_update.

* Remove unused import.

* Add caching for block dict.

* Fix import order.

* Follow types consistently in test.
2023-07-18 23:09:02 +00:00
Jake Lishman 2194f5534d
Refactor output of OpenQASM 3 exporter to use fewer aliases (#10249)
* Refactor output of OpenQASM 3 exporter to use fewer aliases

This removes spurious `_loose_bit` "registers" from the OpenQASM 3
output, and instead emits loose bits with individual `bit` and
`qubit` declarations.  Non-overlapping registers are emitted using
regular `bit[n]` and `qubit[n]` definitions when possible, and we only
resort to aliasing if we must to describe the structure.

This avoids introducing structure to the definitions that does not exist
in the original program, making round-trips and interactions with other
OQ3 consumers more straightforwards.  It's better not to use advanced
features that don't map to hardware particularly well when it's not
necessary.

On the technical side, all bits are now properly tracked in the symbol
table.  Previously, there was a lot of code duplication, internal state
tracking and magic inferences that attempted to "guess" how a
qubit/clbit should be referred to.  Instead, we just properly add them
as variables to the symbol table, which also drastically reduces the
number of objects that effectively reserve names that the user may not
use.

* Remove unnecessary empty init

* Fix typo

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

* Add explicit test of old option

---------

Co-authored-by: Ian Hincks <ian.hincks@ibm.com>
2023-07-18 21:09:58 +00:00
Raynel Sanchez 90c2fe61fa
DAGCircuit: Add get_causal_cone method (#10325)
* Feat: Add `get_causal_node` to `DAGCircuit`:
- Also added `get_qubit_input_node` and `get_qubit_output_node`.

* Test: Added tests to `dagcircuit.py`

* Docs: Added release note

* Chore: Remove type-checking in `dagcircuit.py`
- Type checking was causing strange behavior during linting.

* Added changes to speed up get_causal_cone (#1)

- Replace lists with deque for the iteration.

* Docs: Modify docstring and release note

* Fix: Wrong comparison in `_get_input_output_node`

* Remove: input and output node methods.

* Lint: Fixed formatting

* Docs: Fixed release-note

* Docs: Fixed docstring and release note.

* Fix: Output map double-lookup.

* Docs: Fix inline comments.

* Test: Added test for circuits with barriers

* Refactor: rename to `quantum_causal_cone`

* FIx: Use quantum_sucessors and docstring

---------

Co-authored-by: danielleodigie <97267313+danielleodigie@users.noreply.github.com>
2023-07-18 21:09:22 +00:00
Jake Lishman 35f9e7c462
Remove cyclic-definition handling from `Clifford.from_circuit` (#10441)
* Remove cyclic-definition handling from `Clifford.from_circuit`

This reliance on `RecursionError` could lead to CPython crashing, when
the user had raised the recursion limit beyond what their operating
system could actually support in terms of Python frames.  This was
particularly an issue with Windows when in a context that `jedi` is
active (such as in an IPython session, or if `seaborn` was imported),
since `jedi` unilaterally sets the recursion limit to 3000, while
CPython tends to overflow the stack on Windows at around 2700 frames.

Recursive `definition` fields are not valid data in the Qiskit model, as
the definition is supposed to be hierarchical, and a decomposition in
terms of gates that do not involve the current one in any form.  For
defining equivalences that may involve cycles, one should use the
`EquivalenceLibrary` objects that Terra manages, and the transpiler
takes advantage of via the `BasisTranslator`.

* Remove unused import
2023-07-18 17:23:45 +00:00
ewinston b831bcf627
fix 1q matrix bug in Quantum Shannon Decomposer (#10126)
* fix 1q bug

* formatting

* restrict 2q gates from apply_a2

* Add check that decomposition includes qsd2q gates before optimizing them

Co-authored-by: jsmallz333 <90203920+jsmallz333@users.noreply.github.com>

* Apply suggestions from code review

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

* Add release note for fix to issue 10036

* avoid creating unitary gate if initial gate is 2q

* remove debug code

* Change "certain" to "trivial"

This was requested in a review comment.

---------

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: jsmallz333 <90203920+jsmallz333@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-07-18 17:02:10 +00:00
ewinston 733f78cd7f
add control flow to CommutativeCancellation pass (#9143)
* add initial tests

* tests passing

* remove debug code

* fix test for clbits

* formatting

* Lift creation of PassManager out of loop

In _handle_control_flow_ops, a new PassManager was created for each ControlFlowOp
found. This commit moves the creation out of the loop over nodes. This should be
a bit more efficient.

I also considered mapped_blocks.clear() rather than reallocating. But in some
simpler tests of clearing rather than reallocating, this is actually less performant.
I think reallocating renders the code slightly more understandable.

* Test commutative cancellation does not cross block boundaries

These were requested in a review comment. The previous commit was
also requested in a review comment.

* Add release note for commutative cancellation in control flow blocks

* Include CommutativeAnalysis pass explicitly when doing control flow blocks

A new PassManager for CommutativeCancellation is constructed when descending into control flow blocks.
This commit explicitly includes a CommutativeAnalysis pass in this construction rather than relying on
`requires`. This change, while not necessary, is made for consistency with other explicit constructions
of PassManagers containing these passes.

* Use existing CommutativeCancellation pass in control flow op blocks

A previous commit made a copy of the pass being used in the parent context to be used
in the blocks of a control flow op. With this commit, we reuse the existing pass,
as it is immutable.

* Move import of PassManager from method to top of file

* Revert commit f8c2aaf because I missed a fix already to go

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

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

---------

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-07-18 16:02:06 +00:00
Alberto Maldonado 511a6405d0
Add mid-circuit measurement before conditional operation in random_circuit (#10401)
* Add mid-circuit measurement before conditional operation in random_circuit

* fixed format

* Update releasenotes/notes/fix_9016-2e8bc2cb10b5e204.yaml

Co-authored-by: Eric Arellano <14852634+Eric-Arellano@users.noreply.github.com>

---------

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: Eric Arellano <14852634+Eric-Arellano@users.noreply.github.com>
Co-authored-by: Kevin Krsulich <kevin.krsulich@ibm.com>
2023-07-17 23:30:53 +00:00
Alexander Ivrii 93feba76ea
Linear function usability improvements (#10053)
* contructing linear functions from circuits with barriers and delays; adding __eq__ method

* adding linear function extend_with_identity method

* constructing linear functions from nested circuits

* reorganizing code; constructing linear functions from cliffords (when possible)

* tests for linear functions from cliffords

* linear function from permutation gate

* simplifying condition for checking whether clifford is a linear function

* linear function from another

* pass over release notes

* black

* pylint fixes

* update docstring

* more docstring fixes

* adding pretty-printing functions for linear functions

* adding pretty-printing functions to the release notes

* adding pseudo-random tests

* moving import to the top of the file

* Fix to __eq__ as suggested in review

---------

Co-authored-by: Shelly Garion <46566946+ShellyGarion@users.noreply.github.com>
2023-07-17 13:21:38 +00:00
Luciano Bello 78c6104f9f
Extends SetLayout to take a list (#10344)
* take a list

* tests

* lint

* error handling

* reno

* docs?

* docs!

* docs?!

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-07-13 21:59:21 +00:00
Edwin Navarro eb7530e003
Use rustworkx version of token_swapper (#10001)
* First tests

* Add parallel_threshold

* Convert token_swapper to rustworkx version

* Fix random seed

* Remove unused imports

* Lint

* Skip test and lint

* Upgrade reno, 0.13.0 rustworkx req, and seed change
2023-07-13 21:38:39 +00:00
Kevin Hartman 100a997440
Fix inner qubit mapping in UnitarySynthesis pass. (#10405) 2023-07-13 21:26:56 +00:00
Alexandre 645598a4c0
Fix plot legend don't show up when dataset start with zero (#10176)
* added test to plot_histogram with dataset starting with zero

* fixed plot_histogram

* added docs

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-07-13 20:03:26 +00:00
Luciano Bello b06072d31b
Relax wire_order restrictions in circuit visualization (#9893)
* first attempt

* fixing

* other drawers

* revert test/ipynb/mpl_tester.ipynb

* corner case

* latex test

* reno

* readjust based on https://github.com/Qiskit/qiskit-terra/pull/9893#issuecomment-1494383052

* default complete_wire_order

* test adjustmet

* bug in length

* readjust tests

* ref

* remove old ref

* new ref

* revert https://github.com/Qiskit/qiskit-terra/pull/9893/files#r1259615851

* remove tests because they do not cover the extended code

* reno fix
2023-07-13 12:40:56 +00:00
Willers Yang 9f84f26502
Adding depth-5n synthesis algorithm for -CZ-CX- circuits (#9932)
* Adding depth-5n -CX-CZ- synthesis algorithm

Adding the synthesis algorithm that jointly synthesize a CNOT circuit and CZ circuit in depth 5n by inserting P gates to the CNOT network.

Reference: D. Maslove and W. Yang, "CNOT circuits need little help to implement arbitrary Hadamard-free Clifford transformations they generate," 2022.

https://arxiv.org/abs/2210.16195

* Adding some test cases

* Fixing formatting and docstrings. Updating synth_clifford_depth_lnn

* Update test_clifford_decompose_layers.py

* Fixing some imports

* Fixing more formatting issues

* Add parameter type documentation and minor changes

* adding release note

* Update __init__.py for API

* Updating function name from synth_cx_cz_line_my to synth_cx_cz_depth_line_my

* Updating release note for function name change

* Stylistic changes addressing comments

* Fixing doc strings and adding example to release notes

* Update cx-cz release note with Alex's suggestions

---------

Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>
2023-07-12 05:27:14 +00:00
Kevin Hartman e9c86a5034
Fix `deepcopy` for new-style `Bit` (#10411)
* Make bit copy return self.

* Add release note.

* Preserve existing deepcopy behavior for old bits.

* Add tests to validate copy behaviors.
2023-07-11 11:39:23 +00:00
Diego Emilio Serrano c90a2e7e62
Add `schmidt_decomposition` function to `quantum_info` (#10104)
* add schmidt_decomposition function to states/utils.py

* doc: add docstrings to schmidt_decomposition function

* tox -eblack

* lint changes

* fix qubit ordering definitions in docstring

* add abstol condition to save singular values

* add schmidt_decomposition to __init__.py files in .quantum_info and .quantum_info.states

* add tests for schmidt_decomposition function

* tox lint test

* correct test ordering

* (docs) add schmidt_decomposition to __init__.py docstring

* relabel subsystems in schmidt_decomposition for little-endian consistency

* (test) add test for individual elements of Schmidt decomposition

* tox and lint

* (test) add schmidt component check for 3-level system

* (docs) add reno

* (test) change assertions for schmidt_decomposition tests to AlmostEqual

* (docs) add note to docstring to clarify system partition to perform the decomposition

* (chore) fix typos, lint changes

* separate test functions, check for state with diffprob amps

* eblack lint changes
2023-07-11 02:22:56 +00:00
Pranay Barkataki 2ce71965a6
Adding the feature of calculating entanglement measures negativity (#10134)
* Adding the feature of calculating entanglement measures negativity and logarithmic negativity

* Update docstring of negativity

* Modified the negativity function, where we have removed log negativity

* Modified the doc string of negativity function

* Edited the SVD calculation in the code

---------

Co-authored-by: Payal D. Solanki <solankipayal290696@gmail.com>
2023-07-11 02:20:10 +00:00
Raghav 20ee6ec4ba
Fix `DiagonalGate` QPY serialisation (#10376)
* Update circuits.py

Added "diagonal" in line 282

* added release notes/add-diagonal-to-DiagonalGate-c945e0f8adcd2940

* corrected reformatting using tox

* Added test for diagonal gate.

* Move test to regular unit tests

* Fix DiagonalGate check

* Fixup release note

* Fix test typo

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-07-10 17:53:51 +00:00
Jake Lishman 645eb0ed3f
Add `HAS_PYGMENTS` lazy tester (#9944)
* Add `HAS_PYGMENTS` lazy tester

This somehow slipped through my nets when I added all the lazy testers.
We hope to drop support for the custom Pygments lexers in the future,
but in the mean time, this is the correct way to test for things, and
having an extra lazy tester doesn't hurt us.

* Remove unused import
2023-07-10 15:41:38 +00:00
Matthew Treinish dbf1230aba
Add support for QuantumCircuit.layout to qpy (#10148)
* Add support for QuantumCircuit.layout to qpy

This commit adds the missing support for QuantumCircuit.layout to the
qpy format. This necessitates bumping the QPY format version to 8 to
accomodate the extra data needed for representing the details of the
layout. The tricky piece with representing the 3 TranspileLayout
attributes is representing the virtual bits in the initial layout
because there is no guarantee that the input circuit's registers are in
the output circuit (typically they are not when transpile() is used).

Fixes #10112

* Fix handling of empty layout

* Expand test coverage

* Fix lint

* Add qpy compat tests

* Fix compat tests

* Add release notes

* Adjust layout creation to be register independent

* Finish docs

* Only check layout in compat tests with circuits

* Fix typos

* Fix doc typo in qiskit/qpy/__init__.py

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

* Adjust introduction version for layout qpy compat tests

* Unify qpy compat test version filter style

* Add new line to layout error message

* Simplify serialization logic

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

* Doc fixes

* Improve test coverage

* Don't reuse bits between initial layout and circuit in qpy compat tests.

* Update qiskit/qpy/__init__.py

* Fix test typo

* Use a register in compat tests for consistent equality

* Update test/python/qpy/test_circuit_load_from_qpy.py

---------

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-07-07 20:34:15 +00:00
Jake Lishman 163875e5d7
Fix `CheckMap` with control-flow builder nested conditionals (#10395)
The recursion inside the `CheckMap` pass was based on a custom
`DAGCircuit.compose` solution, rather than the more standard
qubit-argument-binding setup we normally use.  This did not pass in the
clbit ordering to the composition, which could cause it to fail to map
nested conditional statements.

Instead, we can just enter each DAG naturally, and use the regular wire
map to access the physical indices being referred to.
2023-07-06 15:00:54 +00:00
TsafrirA cd770b59f8
Deprecate complex amp support for `ScalableSymbolicPulse` (#10357)
* Deprecate complex amp support for symbolic pulses.

* assembler test fix

* ParameterValueType + release notes edit

* ParameterValueType + release notes edit

* Release notes edit

* Type hints fix
2023-07-05 13:28:24 +00:00
TsafrirA 8a8609f93a
Begin deprecation cycle of the discrete pulse library (#10222)
* Add SymbolicPulse counterparts to the discrete library, and start deprecation process.

* Typo fix

* Release notes styling

* Docs and style corrections

* autosummary update to avoid name clashes

* Remove deprecation section from release notes

* Minor changes to Square()
2023-07-04 05:32:12 +00:00
Matthew Treinish e9f8b7c509
Deprecate namespace packaging hooks (#10322)
* Deprecate namespace packaging hooks

This commit official deprecates the pkgutil namespace hooks that are
used for extending the `qiskit.*` and `qiskit.providers.*` namespaces
from external packages. These were previously used to enable the
elements packaging model where different parts of qiskit lived in
separate python packages under a shared namespace. This is no longer
being used and leaving the namespace extendable by external packages
carries a risk of issues or other accidental cross-interactions when an
external package gets loaded as part of Qiskit.

Fixes ##8809

* Update releasenotes/notes/deprecate-namespace-a2ac600f140755e2.yaml

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

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-06-28 15:49:37 +00:00
Simone Gasperini c6938529b1
Allow multiplication of SparsePauliOp and ParameterExpression (#10264)
* Allow multiplication of SparsePauliOp and ParameterExpression

* Add unit tests for SparsePauliOp and ParameterExpression multiplication

* Add release note for the new feature
2023-06-26 18:18:24 +00:00
Junya Nakamura d67fc2c07a
Deprecate pulse Call instruction (#10247)
* deprecate pulse Call instruction

* Update releasenotes/notes/deprecate-pulse-Call-instruction-538802d8fad7e257.yaml

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

* delete spaces in the releasenote

---------

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2023-06-26 13:12:04 +00:00
Naoki Kanazawa fbd64d95d9
Pass manager refactoring: add passmanager module (#10124)
* Add passmanager module and reorganize transpiler module

* Documentation update

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

* Readd qiskit.transpiler.propertyset

* Documentation update

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>

* BasePass -> GenericPass to avoid name overlap

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
2023-06-23 10:51:12 +00:00
Abby Mitchell 2ba298481a
Added classical_predecessors method (#9980)
* Added classical_predecessors method

* add accesed method

* Added classsical_successor method

* Added classical predecessors and successors method

* added tol command

* successors method

* add test classical_successor method

* changed DagOutNode

* Apply suggestions from code review from @atharva-satpute. Thanks!

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

* add assertRaises on test methods

* correct typo variable name

* change the descrption

* change the text on the example

* change the format of yaml

* new example

* new suggestions

* fix test

* new test example and change the release note

* Fixup release note

* Fix typo

---------

Co-authored-by: Maldoalberto <amaldonador1300@alumno.ipn.mx>
Co-authored-by: Maldoalberto <Alberto.Maldonado.Romo@ibm.com>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: atharva-satpute <55058959+atharva-satpute@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-06-20 16:35:49 +00:00
daniel-fry f9958143eb
Allow to normalize inputs on ``StatePreparation`` and ``Initialize`` (#7189)
* added normalize func

* remove typecheck

* changed to handle numpy arrays and lists both with complex numbers

* Corrected docstring for normalization function

* Add files via upload

* initializer.py normalize function

* fix line endings

* addressing edits in docstrings and normalize function

* review comments

* attempt 1 to fix sphinx

* add reno and improve error message

* fix passing normalize to stateprep

* Fixup PR

---------

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-06-20 15:38:39 +00:00
Artemiy Burov 9ef34b7a46
Add more 1q and 2q Pauli rotation equivalences (#7407)
* added rx to equevalence library

* fixed sign in ry_to_rx

* added rzz to rxx

* gate correction

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

* added ryyrzz, rxxrzz, rzzryy translations, fixed ryrx translation to a more logical variant

* fixed errors

* Add Ryy to Rxx equivalence

* Add release note

---------

Co-authored-by: artemiyburov <artemiy.v.burov@gmail.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-06-20 15:17:17 +00:00
Elena Peña Tapia 93a8172c3c
Fix VQD's `optimal_values` (#10279)
* Fix optimal values

* Add unittest

* Add reno

* Update unittest

* Revert "Update unittest"

This reverts commit 5000d2fb02.

* Update test

* Make test subtest
2023-06-20 08:25:59 +00:00
Matthew Treinish c1866956b2
Remove deprecated InstructionSet circuit_cregs argument (#10302)
This commit removes the deprecated circuit_cregs argument from the
InstructionSet class. This argument was deprecated in the 0.19.0
release and has been supersceded by the resource_requester.
2023-06-16 20:52:01 +00:00
Jake Lishman 45a1d98802
Add standard 1q Pauli equivalences to standard library (#10300)
* Add standard 1q Pauli equivalences to standard library

This makes `transpile` a little more reliable in cases where people are
trying to use it to convert to a constrained basis.  We can't
necessarily recognise _all_ possible transformations into an incomplete
basis, but simple Pauli relations are things people may well expect.

* Fix test setup
2023-06-16 12:50:44 +00:00
Alexandre 5f271bd480
Fix qasm export for gates with same name (#10286)
* added test for inner sequencial custom gates

* fixed quantum circuit qasm test

* fixed qasm method

* added a function to rename the operation

* updated test docstring

* updated recheck operation.name comment

* eblack fix test

* added docs

* lint test

* updated test string format

* Fixup release note

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-06-15 23:25:23 +00:00
Jake Lishman 81964e6499
Fix deprecation warnings emitted by `import qiskit.primitives` (#10287)
The primitives still need to support the legacy
`qiskit.opflow.PauliSumOp` while that object is deprecated but not
removed.  However, we do not want the import of `qiskit.primitives` to
need to import `opflow` to do that, since that will cause the
deprecation warnings emitted by the import of `opflow` to be hidden
(they'll be blamed on Qiskit library code, so hidden by default).

All type-hint usage we can hide behind the `TYPE_CHECKING` static
analysis gate.  For cases where we were actively runtime type-checking
an object, we can gate the `isinstance` check behind a check that
`qiskit.opflow` is already imported; the object cannot be a `PauliSumOp`
if the module isn't initialised.
2023-06-15 13:09:52 +00:00
Evan McKinney 7df290b8f3
Fix BasicSwap FakeRun Typo (#10274)
* fix typo, issue #10147

* create basicswap fake_run test

* release note for #10149 fix

* ensure fake_run modifes layout prop, not the circuit logic

* black formatting, test_basic_swap
2023-06-14 10:24:33 +00:00
Jake Lishman 86df15d3b9
Improve casting and error message for `ParameterExpression` (#10244)
* Improve casting and error message for `ParameterExpression`

Previously, we assumed that the only reason a cast of
`ParameterExpression` to `complex`/`float`/`int` could fail was because
of unbound parameters, and emitted an error accordingly.  This is not
the case; a fully bound complex value will still fail to convert to
`float`.

This PR improves the error messages in these cases, and works around a
difference of Sympy and Symengine, where the latter will fail to convert
real-valued expressions that were symbollically complex at some point in
their binding history to `float`.  Sympy more reliably reduces values
down to real-only values when the imaginary part is exactly cancelled,
which is a use-case our users tend to expect.

* Fix typo in test

* Update releasenotes/notes/parameter-float-cast-48f3731fec5e47cd.yaml

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

---------

Co-authored-by: Kevin Hartman <kevin@hart.mn>
2023-06-12 18:08:20 +00:00
Kento Ueda a1615a864f
Dispatch a builder with backendV1 and backendV2 (#10150)
* fix measure_v2

* modify measure_all

* dispatch backend

* add test of the builder with backendV2

* reconfigure test codes and some func

* refactoring

* add reno

* fix _measure_v2

* fix backend.meas_map in measure_v2

* fix reno

* delete get_qubit_channels from utils

* add get_qubits_channels in qubit_channels

* recostruct test about the builder with backendV2

* fix descriptions of test_macros

* fix descriptions of test_macros again

* delete import of backendV2 in utils

* revert no need to modify code

* Update releasenotes/notes/fix-dispatching-backends-28aff96f726ca9c5.yaml

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

* Update a commnet in qiskit/pulse/builder.py

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

* remove import TYPE_CHECKING

* removed test_builder.py utils.py and test_analyzation.py from pull request

---------

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2023-06-12 16:17:23 +00:00
Matthew Treinish c463b3c474
Use stable Python C API for building Rust extension (#10120)
* Use stable Python C API for building Rust extension

This commit tweaks the rust extension code to start using the PyO3 abi3
flag to build binaries that are compatible with all python versions, not
just a single release. Previously, we were building against the version
specific C API and that resulted in needing abinary file for each
supported python version on each supported platform/architecture. By
using the abi3 feature flag and marking the wheels as being built with
the limited api we can reduce our packaging overhead to just having one
wheel file per supported platform/architecture.

The only real code change needed here was to update the memory
marginalization function. PyO3's abi3 feature is incompatible with
returning a big int object from rust (the C API they use for that
conversion isn't part of the stable C API). So this commit updates the
function to convert to create a python int manually using the PyO3 api
where that was being done before.

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

* Set minimum version on abi3 flag to Python 3.8

* Fix lint

* Use py_limited_api="auto" on RustExtension

According to the docs for the setuptools-rust RustExtension class:
https://setuptools-rust.readthedocs.io/en/latest/reference.html#setuptools_rust.RustExtension
The best setting to use for the py_limited_api argument is `"auto"` as
this will use the setting in the PyO3 module to determine the correct
value to set. This commit updates the setup.py to follow the
recommendation in the docs.

* Update handling of phase input to expval rust calls

The pauli_expval module in Rust that Statevector and DensityMatrix
leverage when computing defines the input type of the phase argument as
Complex64. Previously, the quantum info code in the Statevector and
DensityMatrix classes were passing in a 1 element ndarray for this
parameter. When using the the version specific Python C API in pyo3 it
would convert the single element array to a scalar value. However when
using abi3 this handling was not done (or was not done correctly) and
this caused the tests to fail. This commit updates the quantum info
module to pass the phase as a complex value instead of a 1 element numpy
array to bypass this behavior change in PyO3 when using abi3.

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

* Set py_limited_api explicitly to True

* DNM: Test cibuildwheel works with abi3

* Add abi3audit to cibuildwheel repair step

* Force setuptools to use abi3 tag

* Add wheel to sdist build

* Workaround abiaudit3 not moving wheels and windows not having a default repair command

* Add source of setup.py hack

* Add comment about pending pyo3 abi3 bigint support

* Revert "DNM: Test cibuildwheel works with abi3"

This reverts commit 8ca24cf1e4.

* Add release note

* Simplify setting abi3 tag in built wheels

* Update releasenotes/notes/use-abi3-4a935e0557d3833b.yaml

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

* Update release note

* Update releasenotes/notes/use-abi3-4a935e0557d3833b.yaml

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
2023-06-12 13:45:27 +00:00
Daniel J. Egger b36609befd
FullAncillaAllocation for backends witout a coupling map (#10240)
* * Added support for targets without a coupling map.

* * Removed restrictive raise.

* * Changed order of target and coupling map

* Apply suggestions from code review

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

---------

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2023-06-09 18:59:25 +00:00
Kento Ueda f91136654b
Fix the output macros.measure with backendV2 (#10135)
* fix measure_v2

* modify measure_all

* fix meas_map input in measure_v2

* add reno

* fix reno

* Update reno.

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

* fix reno again

---------

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2023-06-07 11:29:01 +00:00
Junya Nakamura 2d8300c834
Support instruction filtering method in ScheduleBlock class (#9971)
* activate filter method in ScheduleBlock class

* use functools.singledispatch

* add tests for filter method in ScheduleBlock class

* filter out empty schedule_blocks

* update doc

* rm logical_and

* add catch-TypeError functions decorated with singledispatch

* use pulse builder in test

* make another test function for nested block

* add a release note

* Rm optional args

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

* add warning

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

* update the release note

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

* activate exclude method in ScheduleBlock class

---------

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
2023-06-07 11:03:04 +00:00
Mu-Te Joshua Lau 84d13d7795
Fix QuantumCircuit.draw() not outputting pdf in latex mode (#10212)
* Fix QuantumCircuit.draw() not outputting pdf in latex mode

* Added bugfix release note; moved import to the top

* Fixup release note

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-06-06 15:29:43 +00:00
Diego Emilio Serrano 6f29d7be78
Fix output of `DensityMatrix.partial_transpose` to match input dimensions (#10163)
* (fix) change output of partial_transpose to return DensityMatrix matching input dimensions

* (test) check output dims match input dims when using DensityMatrix.partial_transpose

* (docs) add bugfix reno

* lint changes

* Fix up release note

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-06-06 13:49:28 +00:00
Will Shanks 332bd9fe0b
Assign values directly to fully bound parameters in quantum circuits (#10183)
* Assign circuit parameters as int/float to instructions

* Do not test that fully bound parameters are still ParameterExpressions

* Change int to float in qasm output

pi_check casts integers to floats but not integers inside
ParameterExpressions.

* Workaround symengine ComplexDouble not supporting float

* black

* Update releasenotes/notes/circuit-assign-parameter-to-concrete-value-7cad75c97183257f.yaml

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

* Update releasenotes/notes/circuit-assign-parameter-to-concrete-value-7cad75c97183257f.yaml

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

* Restore assigned parameter value type check to tests

* Add test to check type and value of simple circuit parameter assignment

* Add consistency check between assigned instruction data and calibrations dict keys

* Add regression test

* Add upgrade note

* Remove support for complex instruction parameter assignment

* Restore complex assignment

Complex assignment maybe not be supported but allowing it in the
parameter assignment step lets validate_parameters get the value and
raise an appropriate exception.

* black

* More specific assertion methods

* Use exact floating-point check

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2023-06-01 19:00:25 +00:00
John Lapeyre 174b661d57
Fix unitary synthesis for parameterized basis gates in Target (#10090)
* Fix unitary synthesis for parameterized basis gates in Target

Replace parameterized RXX with RXX(pi / 2) and parameterized RZX with RZX(pi / 4).

* Run black

* Fix dict ordering problem between linux and windows

* Remove unused import

* Try using seed in call to transpile to fix CI fail

Linux and MacOS give one result and Windows another

* Add comments explaining no symbolic gates can be sent to 2q decomposers

* Make test for synthesis in with parameterized basis gate less strict

Windows on the one hand, and MacOS and Linux on other give different circuits
in a simple test of synthesis. Both are correct. This commit makes the test less strict.

* Add release note for fix-issue-10082
2023-06-01 13:17:20 +00:00
Matthew Treinish 4762e26708
Fix PassManagerConfig.from_backend with BackendV1 and no CouplingMap (#10172)
* Fix PassManagerConfig.from_backend with BackendV1 and no CouplingMap

This commit fixes an issue in the PassManagerConfig.from_backend
constructor method when using BackendV1 based simulator backends. The
pass was incorrectly handling the case when the backend configuration
didn't have a coupling map defined and incorrectly creating a coupling
map with 0 qubits instead of using None to indicate the lack of
connectivity. This has been fixed so the coupling map creation is
skipped if there is no coupling map attribute in the backend's
configuration.

Fixes #10171

* Fix tests
2023-05-30 17:21:47 +00:00
Jake Lishman 76850e1fdf
Fix top-level `switch` statements in `QuantumCircuit.compose` (#10164)
* Fix top-level `switch` statements in `QuantumCircuit.compose`

The register-mapping code was not being applied to `SwitchCaseOp.target`
in the same way that it is for conditions.  This commit does not change
any behaviour about recursing into _nested_ control-flow blocks, which
still likely have problems with composition.

* Apply suggestions from review
2023-05-30 16:33:06 +00:00
Alexander Ivrii 788b89d985
Fixing BlockCollapser with Clbits (#9823)
* Bug fix: collapsing blocks with clbits

Co-authored-by: chriseclectic <cjwood@us.ibm.com>

* release notes

* similar fix to DAGDependency

* additional fixes to handle classical bits in conditions

* fixing lint issue

* Fixing handling of conditions over full registers, following review comments

---------

Co-authored-by: chriseclectic <cjwood@us.ibm.com>
2023-05-26 18:49:15 +00:00
Jake Lishman 716b648cb9
Fix `initial_layout` in `transpile` with loose qubits (#10153)
The previous logic around building a `Layout` object from an
`initial_layout` was still couched in the "registers own bits" model, so
could not cope with loose bits.  It's most convenient to just build the
mapping ourselves during the parsing, since the logic is quite specific
to the form of the `initial_layout` argument, rather than being
something that's inherently tied to the `Layout` class.
2023-05-24 19:31:30 +00:00
Evgenii Zheltonozhskii 02502b5d98
Remove undefined variable (#10117)
* Remove undefined variable (fix https://github.com/Qiskit/qiskit-terra/issues/10113)

* Add test and bugfix description
2023-05-24 12:28:01 +00:00